blob: 580ecaab61037b3bf92351a18e43ef8d3cfd526f [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
41#include "talk/base/base64.h"
42#include "talk/base/byteorder.h"
43#include "talk/base/common.h"
44#include "talk/base/helpers.h"
45#include "talk/base/logging.h"
46#include "talk/base/stringencode.h"
47#include "talk/base/stringutils.h"
48#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.h"
53#include "webrtc/modules/audio_processing/include/audio_processing.h"
54
55#ifdef WIN32
56#include <objbase.h> // NOLINT
57#endif
58
59namespace cricket {
60
61struct CodecPref {
62 const char* name;
63 int clockrate;
64 int channels;
65 int payload_type;
66 bool is_multi_rate;
67};
68
69static const CodecPref kCodecPrefs[] = {
70 { "OPUS", 48000, 2, 111, true },
71 { "ISAC", 16000, 1, 103, true },
72 { "ISAC", 32000, 1, 104, true },
73 { "CELT", 32000, 1, 109, true },
74 { "CELT", 32000, 2, 110, true },
75 { "G722", 16000, 1, 9, false },
76 { "ILBC", 8000, 1, 102, false },
77 { "PCMU", 8000, 1, 0, false },
78 { "PCMA", 8000, 1, 8, false },
79 { "CN", 48000, 1, 107, false },
80 { "CN", 32000, 1, 106, false },
81 { "CN", 16000, 1, 105, false },
82 { "CN", 8000, 1, 13, false },
83 { "red", 8000, 1, 127, false },
84 { "telephone-event", 8000, 1, 126, false },
85};
86
87// For Linux/Mac, using the default device is done by specifying index 0 for
88// VoE 4.0 and not -1 (which was the case for VoE 3.5).
89//
90// On Windows Vista and newer, Microsoft introduced the concept of "Default
91// Communications Device". This means that there are two types of default
92// devices (old Wave Audio style default and Default Communications Device).
93//
94// On Windows systems which only support Wave Audio style default, uses either
95// -1 or 0 to select the default device.
96//
97// On Windows systems which support both "Default Communication Device" and
98// old Wave Audio style default, use -1 for Default Communications Device and
99// -2 for Wave Audio style default, which is what we want to use for clips.
100// It's not clear yet whether the -2 index is handled properly on other OSes.
101
102#ifdef WIN32
103static const int kDefaultAudioDeviceId = -1;
104static const int kDefaultSoundclipDeviceId = -2;
105#else
106static const int kDefaultAudioDeviceId = 0;
107#endif
108
109// extension header for audio levels, as defined in
110// http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03
111static const char kRtpAudioLevelHeaderExtension[] =
112 "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
113static const int kRtpAudioLevelHeaderExtensionId = 1;
114
115static const char kIsacCodecName[] = "ISAC";
116static const char kL16CodecName[] = "L16";
117// Codec parameters for Opus.
118static const int kOpusMonoBitrate = 32000;
119// Parameter used for NACK.
120// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
121static const int kNackMaxPackets = 250;
122static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000123// draft-spittka-payload-rtp-opus-03
124// Opus bitrate should be in the range between 6000 and 510000.
125static const int kOpusMinBitrate = 6000;
126static const int kOpusMaxBitrate = 510000;
127
128#if defined(CHROMEOS)
129// Ensure we open the file in a writeable path on ChromeOS. This workaround
130// can be removed when it's possible to specify a filename for audio option
131// based AEC dumps.
132//
133// TODO(grunell): Use a string in the options instead of hardcoding it here
134// and let the embedder choose the filename (crbug.com/264223).
135//
136// NOTE(ajm): Don't use this hardcoded /tmp path on non-ChromeOS platforms.
137static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
138#else
139static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
140#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000141
142// Dumps an AudioCodec in RFC 2327-ish format.
143static std::string ToString(const AudioCodec& codec) {
144 std::stringstream ss;
145 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
146 << " (" << codec.id << ")";
147 return ss.str();
148}
149static std::string ToString(const webrtc::CodecInst& codec) {
150 std::stringstream ss;
151 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
152 << " (" << codec.pltype << ")";
153 return ss.str();
154}
155
156static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
157 const char* delim = "\r\n";
158 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
159 LOG_V(sev) << tok;
160 }
161}
162
163// Severity is an integer because it comes is assumed to be from command line.
164static int SeverityToFilter(int severity) {
165 int filter = webrtc::kTraceNone;
166 switch (severity) {
167 case talk_base::LS_VERBOSE:
168 filter |= webrtc::kTraceAll;
169 case talk_base::LS_INFO:
170 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
171 case talk_base::LS_WARNING:
172 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
173 case talk_base::LS_ERROR:
174 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
175 }
176 return filter;
177}
178
179static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
180 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
181 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
182 kCodecPrefs[i].clockrate == codec.plfreq) {
183 return kCodecPrefs[i].is_multi_rate;
184 }
185 }
186 return false;
187}
188
189static bool FindCodec(const std::vector<AudioCodec>& codecs,
190 const AudioCodec& codec,
191 AudioCodec* found_codec) {
192 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
193 it != codecs.end(); ++it) {
194 if (it->Matches(codec)) {
195 if (found_codec != NULL) {
196 *found_codec = *it;
197 }
198 return true;
199 }
200 }
201 return false;
202}
203static bool IsNackEnabled(const AudioCodec& codec) {
204 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
205 kParamValueEmpty));
206}
207
208
209class WebRtcSoundclipMedia : public SoundclipMedia {
210 public:
211 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
212 : engine_(engine), webrtc_channel_(-1) {
213 engine_->RegisterSoundclip(this);
214 }
215
216 virtual ~WebRtcSoundclipMedia() {
217 engine_->UnregisterSoundclip(this);
218 if (webrtc_channel_ != -1) {
219 // We shouldn't have to call Disable() here. DeleteChannel() should call
220 // StopPlayout() while deleting the channel. We should fix the bug
221 // inside WebRTC and remove the Disable() call bellow. This work is
222 // tracked by bug http://b/issue?id=5382855.
223 PlaySound(NULL, 0, 0);
224 Disable();
225 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
226 == -1) {
227 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
228 }
229 }
230 }
231
232 bool Init() {
233 webrtc_channel_ = engine_->voe_sc()->base()->CreateChannel();
234 if (webrtc_channel_ == -1) {
235 LOG_RTCERR0(CreateChannel);
236 return false;
237 }
238 return true;
239 }
240
241 bool Enable() {
242 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
243 LOG_RTCERR1(StartPlayout, webrtc_channel_);
244 return false;
245 }
246 return true;
247 }
248
249 bool Disable() {
250 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
251 LOG_RTCERR1(StopPlayout, webrtc_channel_);
252 return false;
253 }
254 return true;
255 }
256
257 virtual bool PlaySound(const char *buf, int len, int flags) {
258 // The voe file api is not available in chrome.
259 if (!engine_->voe_sc()->file()) {
260 return false;
261 }
262 // Must stop playing the current sound (if any), because we are about to
263 // modify the stream.
264 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
265 == -1) {
266 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
267 return false;
268 }
269
270 if (buf) {
271 stream_.reset(new WebRtcSoundclipStream(buf, len));
272 stream_->set_loop((flags & SF_LOOP) != 0);
273 stream_->Rewind();
274
275 // Play it.
276 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
277 webrtc_channel_, stream_.get()) == -1) {
278 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
279 LOG(LS_ERROR) << "Unable to start soundclip";
280 return false;
281 }
282 } else {
283 stream_.reset();
284 }
285 return true;
286 }
287
288 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
289
290 private:
291 WebRtcVoiceEngine *engine_;
292 int webrtc_channel_;
293 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
294};
295
296WebRtcVoiceEngine::WebRtcVoiceEngine()
297 : voe_wrapper_(new VoEWrapper()),
298 voe_wrapper_sc_(new VoEWrapper()),
299 tracing_(new VoETraceWrapper()),
300 adm_(NULL),
301 adm_sc_(NULL),
302 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
303 is_dumping_aec_(false),
304 desired_local_monitor_enable_(false),
305 tx_processor_ssrc_(0),
306 rx_processor_ssrc_(0) {
307 Construct();
308}
309
310WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
311 VoEWrapper* voe_wrapper_sc,
312 VoETraceWrapper* tracing)
313 : voe_wrapper_(voe_wrapper),
314 voe_wrapper_sc_(voe_wrapper_sc),
315 tracing_(tracing),
316 adm_(NULL),
317 adm_sc_(NULL),
318 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
319 is_dumping_aec_(false),
320 desired_local_monitor_enable_(false),
321 tx_processor_ssrc_(0),
322 rx_processor_ssrc_(0) {
323 Construct();
324}
325
326void WebRtcVoiceEngine::Construct() {
327 SetTraceFilter(log_filter_);
328 initialized_ = false;
329 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
330 SetTraceOptions("");
331 if (tracing_->SetTraceCallback(this) == -1) {
332 LOG_RTCERR0(SetTraceCallback);
333 }
334 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
335 LOG_RTCERR0(RegisterVoiceEngineObserver);
336 }
337 // Clear the default agc state.
338 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
339
340 // Load our audio codec list.
341 ConstructCodecs();
342
343 // Load our RTP Header extensions.
344 rtp_header_extensions_.push_back(
345 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
346 kRtpAudioLevelHeaderExtensionId));
347}
348
349static bool IsOpus(const AudioCodec& codec) {
350 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
351}
352
353static bool IsIsac(const AudioCodec& codec) {
354 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
355}
356
357// True if params["stereo"] == "1"
358static bool IsOpusStereoEnabled(const AudioCodec& codec) {
359 CodecParameterMap::const_iterator param =
360 codec.params.find(kCodecParamStereo);
361 if (param == codec.params.end()) {
362 return false;
363 }
364 return param->second == kParamValueTrue;
365}
366
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000367static bool IsValidOpusBitrate(int bitrate) {
368 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
369}
370
371// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
372// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
373static int GetOpusBitrateFromParams(const AudioCodec& codec) {
374 int bitrate = 0;
375 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
376 return 0;
377 }
378 if (!IsValidOpusBitrate(bitrate)) {
379 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
380 << "invalid value: " << bitrate;
381 return 0;
382 }
383 return bitrate;
384}
385
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000386void WebRtcVoiceEngine::ConstructCodecs() {
387 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
388 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
389 for (int i = 0; i < ncodecs; ++i) {
390 webrtc::CodecInst voe_codec;
391 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
392 // Skip uncompressed formats.
393 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
394 continue;
395 }
396
397 const CodecPref* pref = NULL;
398 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
399 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
400 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
401 kCodecPrefs[j].channels == voe_codec.channels) {
402 pref = &kCodecPrefs[j];
403 break;
404 }
405 }
406
407 if (pref) {
408 // Use the payload type that we've configured in our pref table;
409 // use the offset in our pref table to determine the sort order.
410 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
411 voe_codec.rate, voe_codec.channels,
412 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
413 LOG(LS_INFO) << ToString(codec);
414 if (IsIsac(codec)) {
415 // Indicate auto-bandwidth in signaling.
416 codec.bitrate = 0;
417 }
418 if (IsOpus(codec)) {
419 // Only add fmtp parameters that differ from the spec.
420 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
421 codec.params[kCodecParamMinPTime] =
422 talk_base::ToString(kPreferredMinPTime);
423 }
424 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
425 codec.params[kCodecParamMaxPTime] =
426 talk_base::ToString(kPreferredMaxPTime);
427 }
428 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
429 // when they can be set to values other than the default.
430 }
431 codecs_.push_back(codec);
432 } else {
433 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
434 }
435 }
436 }
437 // Make sure they are in local preference order.
438 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
439}
440
441WebRtcVoiceEngine::~WebRtcVoiceEngine() {
442 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
443 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
444 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
445 }
446 if (adm_) {
447 voe_wrapper_.reset();
448 adm_->Release();
449 adm_ = NULL;
450 }
451 if (adm_sc_) {
452 voe_wrapper_sc_.reset();
453 adm_sc_->Release();
454 adm_sc_ = NULL;
455 }
456
457 // Test to see if the media processor was deregistered properly
458 ASSERT(SignalRxMediaFrame.is_empty());
459 ASSERT(SignalTxMediaFrame.is_empty());
460
461 tracing_->SetTraceCallback(NULL);
462}
463
464bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
465 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
466 bool res = InitInternal();
467 if (res) {
468 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
469 } else {
470 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
471 Terminate();
472 }
473 return res;
474}
475
476bool WebRtcVoiceEngine::InitInternal() {
477 // Temporarily turn logging level up for the Init call
478 int old_filter = log_filter_;
479 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
480 SetTraceFilter(extended_filter);
481 SetTraceOptions("");
482
483 // Init WebRtc VoiceEngine.
484 if (voe_wrapper_->base()->Init(adm_) == -1) {
485 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
486 SetTraceFilter(old_filter);
487 return false;
488 }
489
490 SetTraceFilter(old_filter);
491 SetTraceOptions(log_options_);
492
493 // Log the VoiceEngine version info
494 char buffer[1024] = "";
495 voe_wrapper_->base()->GetVersion(buffer);
496 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
497 LogMultiline(talk_base::LS_INFO, buffer);
498
499 // Save the default AGC configuration settings. This must happen before
500 // calling SetOptions or the default will be overwritten.
501 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
502 LOG_RTCERR0(GetAGCConfig);
503 return false;
504 }
505
506 if (!SetOptions(MediaEngineInterface::DEFAULT_AUDIO_OPTIONS)) {
507 return false;
508 }
509
510 // Print our codec list again for the call diagnostic log
511 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
512 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
513 it != codecs_.end(); ++it) {
514 LOG(LS_INFO) << ToString(*it);
515 }
516
517#if defined(LINUX) && !defined(HAVE_LIBPULSE)
518 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
519#endif
520
521 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
522 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
523 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
524 return false;
525 }
526
527 // On Windows, tell it to use the default sound (not communication) devices.
528 // First check whether there is a valid sound device for playback.
529 // TODO(juberti): Clean this up when we support setting the soundclip device.
530#ifdef WIN32
531 // The SetPlayoutDevice may not be implemented in the case of external ADM.
532 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
533 // PeerConnection interface never set the adm_sc_, so need to check both
534 // in order to determine if the external adm is used.
535 if (!adm_ && !adm_sc_) {
536 int num_of_devices = 0;
537 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
538 num_of_devices > 0) {
539 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
540 == -1) {
541 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
542 voe_wrapper_sc_->error());
543 return false;
544 }
545 } else {
546 LOG(LS_WARNING) << "No valid sound playout device found.";
547 }
548 }
549#endif
550
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000551 // Disable the DTMF playout when a tone is sent.
552 // PlayDtmfTone will be used if local playout is needed.
553 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
554 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
555 }
556
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000557 initialized_ = true;
558 return true;
559}
560
561void WebRtcVoiceEngine::Terminate() {
562 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
563 initialized_ = false;
564
565 StopAecDump();
566
567 voe_wrapper_sc_->base()->Terminate();
568 voe_wrapper_->base()->Terminate();
569 desired_local_monitor_enable_ = false;
570}
571
572int WebRtcVoiceEngine::GetCapabilities() {
573 return AUDIO_SEND | AUDIO_RECV;
574}
575
576VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
577 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
578 if (!ch->valid()) {
579 delete ch;
580 ch = NULL;
581 }
582 return ch;
583}
584
585SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
586 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
587 if (!soundclip->Init() || !soundclip->Enable()) {
588 delete soundclip;
589 return NULL;
590 }
591 return soundclip;
592}
593
594// TODO(zhurunz): Add a comprehensive unittests for SetOptions().
595bool WebRtcVoiceEngine::SetOptions(int flags) {
596 AudioOptions options;
597
598 // Convert flags to AudioOptions.
599 options.echo_cancellation.Set(
600 ((flags & MediaEngineInterface::ECHO_CANCELLATION) != 0));
601 options.auto_gain_control.Set(
602 ((flags & MediaEngineInterface::AUTO_GAIN_CONTROL) != 0));
603 options.noise_suppression.Set(
604 ((flags & MediaEngineInterface::NOISE_SUPPRESSION) != 0));
605 options.highpass_filter.Set(
606 ((flags & MediaEngineInterface::HIGHPASS_FILTER) != 0));
607 options.stereo_swapping.Set(
608 ((flags & MediaEngineInterface::STEREO_FLIPPING) != 0));
609
610 // Set defaults for flagless options here. Make sure they are all set so that
611 // ApplyOptions applies all of them when we clear overrides.
612 options.typing_detection.Set(true);
613 options.conference_mode.Set(false);
614 options.adjust_agc_delta.Set(0);
615 options.experimental_agc.Set(false);
616 options.experimental_aec.Set(false);
617 options.aec_dump.Set(false);
618
619 return SetAudioOptions(options);
620}
621
622bool WebRtcVoiceEngine::SetAudioOptions(const AudioOptions& options) {
623 if (!ApplyOptions(options)) {
624 return false;
625 }
626 options_ = options;
627 return true;
628}
629
630bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
631 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
632 if (!ApplyOptions(overrides)) {
633 return false;
634 }
635 option_overrides_ = overrides;
636 return true;
637}
638
639bool WebRtcVoiceEngine::ClearOptionOverrides() {
640 LOG(LS_INFO) << "Clearing option overrides.";
641 AudioOptions options = options_;
642 // Only call ApplyOptions if |options_overrides_| contains overrided options.
643 // ApplyOptions affects NS, AGC other options that is shared between
644 // all WebRtcVoiceEngineChannels.
645 if (option_overrides_ == AudioOptions()) {
646 return true;
647 }
648
649 if (!ApplyOptions(options)) {
650 return false;
651 }
652 option_overrides_ = AudioOptions();
653 return true;
654}
655
656// AudioOptions defaults are set in InitInternal (for options with corresponding
657// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
658bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
659 AudioOptions options = options_in; // The options are modified below.
660 // kEcConference is AEC with high suppression.
661 webrtc::EcModes ec_mode = webrtc::kEcConference;
662 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
663 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
664 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
665 bool aecm_comfort_noise = false;
666
667#if defined(IOS)
668 // On iOS, VPIO provides built-in EC and AGC.
669 options.echo_cancellation.Set(false);
670 options.auto_gain_control.Set(false);
671#elif defined(ANDROID)
672 ec_mode = webrtc::kEcAecm;
673#endif
674
675#if defined(IOS) || defined(ANDROID)
676 // Set the AGC mode for iOS as well despite disabling it above, to avoid
677 // unsupported configuration errors from webrtc.
678 agc_mode = webrtc::kAgcFixedDigital;
679 options.typing_detection.Set(false);
680 options.experimental_agc.Set(false);
681 options.experimental_aec.Set(false);
682#endif
683
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000684
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
686
687 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
688
689 bool echo_cancellation;
690 if (options.echo_cancellation.Get(&echo_cancellation)) {
691 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
692 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
693 return false;
694 }
695#if !defined(ANDROID)
696 // TODO(ajm): Remove the error return on Android from webrtc.
697 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
698 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
699 return false;
700 }
701#endif
702 if (ec_mode == webrtc::kEcAecm) {
703 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
704 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
705 return false;
706 }
707 }
708 }
709
710 bool auto_gain_control;
711 if (options.auto_gain_control.Get(&auto_gain_control)) {
712 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
713 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
714 return false;
715 }
716 }
717
718 bool noise_suppression;
719 if (options.noise_suppression.Get(&noise_suppression)) {
720 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
721 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
722 return false;
723 }
724 }
725
726 bool highpass_filter;
727 if (options.highpass_filter.Get(&highpass_filter)) {
728 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
729 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
730 return false;
731 }
732 }
733
734 bool stereo_swapping;
735 if (options.stereo_swapping.Get(&stereo_swapping)) {
736 voep->EnableStereoChannelSwapping(stereo_swapping);
737 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
738 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
739 return false;
740 }
741 }
742
743 bool typing_detection;
744 if (options.typing_detection.Get(&typing_detection)) {
745 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
746 // In case of error, log the info and continue
747 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
748 }
749 }
750
751 int adjust_agc_delta;
752 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
753 if (!AdjustAgcLevel(adjust_agc_delta)) {
754 return false;
755 }
756 }
757
758 bool aec_dump;
759 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000760 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000761 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 else
763 StopAecDump();
764 }
765
766
767 return true;
768}
769
770bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
771 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
772 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
773 LOG_RTCERR1(SetDelayOffsetMs, offset);
774 return false;
775 }
776
777 return true;
778}
779
780struct ResumeEntry {
781 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
782 : channel(c),
783 playout(p),
784 send(s) {
785 }
786
787 WebRtcVoiceMediaChannel *channel;
788 bool playout;
789 SendFlags send;
790};
791
792// TODO(juberti): Refactor this so that the core logic can be used to set the
793// soundclip device. At that time, reinstate the soundclip pause/resume code.
794bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
795 const Device* out_device) {
796#if !defined(IOS) && !defined(ANDROID)
797 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
798 kDefaultAudioDeviceId;
799 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
800 kDefaultAudioDeviceId;
801 // The device manager uses -1 as the default device, which was the case for
802 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
803#ifndef WIN32
804 if (-1 == in_id) {
805 in_id = kDefaultAudioDeviceId;
806 }
807 if (-1 == out_id) {
808 out_id = kDefaultAudioDeviceId;
809 }
810#endif
811
812 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
813 in_device->name : "Default device";
814 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
815 out_device->name : "Default device";
816 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
817 << ") and speaker to (id=" << out_id << ", name=" << out_name
818 << ")";
819
820 // If we're running the local monitor, we need to stop it first.
821 bool ret = true;
822 if (!PauseLocalMonitor()) {
823 LOG(LS_WARNING) << "Failed to pause local monitor";
824 ret = false;
825 }
826
827 // Must also pause all audio playback and capture.
828 for (ChannelList::const_iterator i = channels_.begin();
829 i != channels_.end(); ++i) {
830 WebRtcVoiceMediaChannel *channel = *i;
831 if (!channel->PausePlayout()) {
832 LOG(LS_WARNING) << "Failed to pause playout";
833 ret = false;
834 }
835 if (!channel->PauseSend()) {
836 LOG(LS_WARNING) << "Failed to pause send";
837 ret = false;
838 }
839 }
840
841 // Find the recording device id in VoiceEngine and set recording device.
842 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
843 ret = false;
844 }
845 if (ret) {
846 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
847 LOG_RTCERR2(SetRecordingDevice, in_device->name, in_id);
848 ret = false;
849 }
850 }
851
852 // Find the playout device id in VoiceEngine and set playout device.
853 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
854 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
855 ret = false;
856 }
857 if (ret) {
858 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
859 LOG_RTCERR2(SetPlayoutDevice, out_device->name, out_id);
860 ret = false;
861 }
862 }
863
864 // Resume all audio playback and capture.
865 for (ChannelList::const_iterator i = channels_.begin();
866 i != channels_.end(); ++i) {
867 WebRtcVoiceMediaChannel *channel = *i;
868 if (!channel->ResumePlayout()) {
869 LOG(LS_WARNING) << "Failed to resume playout";
870 ret = false;
871 }
872 if (!channel->ResumeSend()) {
873 LOG(LS_WARNING) << "Failed to resume send";
874 ret = false;
875 }
876 }
877
878 // Resume local monitor.
879 if (!ResumeLocalMonitor()) {
880 LOG(LS_WARNING) << "Failed to resume local monitor";
881 ret = false;
882 }
883
884 if (ret) {
885 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
886 << ") and speaker to (id="<< out_id << " name=" << out_name
887 << ")";
888 }
889
890 return ret;
891#else
892 return true;
893#endif // !IOS && !ANDROID
894}
895
896bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
897 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
898 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
899#ifdef LINUX
900 *rtc_id = dev_id;
901 return true;
902#else
903 // In Windows and Mac, we need to find the VoiceEngine device id by name
904 // unless the input dev_id is the default device id.
905 if (kDefaultAudioDeviceId == dev_id) {
906 *rtc_id = dev_id;
907 return true;
908 }
909
910 // Get the number of VoiceEngine audio devices.
911 int count = 0;
912 if (is_input) {
913 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
914 LOG_RTCERR0(GetNumOfRecordingDevices);
915 return false;
916 }
917 } else {
918 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
919 LOG_RTCERR0(GetNumOfPlayoutDevices);
920 return false;
921 }
922 }
923
924 for (int i = 0; i < count; ++i) {
925 char name[128];
926 char guid[128];
927 if (is_input) {
928 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
929 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
930 } else {
931 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
932 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
933 }
934
935 std::string webrtc_name(name);
936 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
937 *rtc_id = i;
938 return true;
939 }
940 }
941 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
942 return false;
943#endif
944}
945
946bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
947 unsigned int ulevel;
948 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
949 LOG_RTCERR1(GetSpeakerVolume, level);
950 return false;
951 }
952 *level = ulevel;
953 return true;
954}
955
956bool WebRtcVoiceEngine::SetOutputVolume(int level) {
957 ASSERT(level >= 0 && level <= 255);
958 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
959 LOG_RTCERR1(SetSpeakerVolume, level);
960 return false;
961 }
962 return true;
963}
964
965int WebRtcVoiceEngine::GetInputLevel() {
966 unsigned int ulevel;
967 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
968 static_cast<int>(ulevel) : -1;
969}
970
971bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
972 desired_local_monitor_enable_ = enable;
973 return ChangeLocalMonitor(desired_local_monitor_enable_);
974}
975
976bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
977 // The voe file api is not available in chrome.
978 if (!voe_wrapper_->file()) {
979 return false;
980 }
981 if (enable && !monitor_) {
982 monitor_.reset(new WebRtcMonitorStream);
983 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
984 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
985 // Must call Stop() because there are some cases where Start will report
986 // failure but still change the state, and if we leave VE in the on state
987 // then it could crash later when trying to invoke methods on our monitor.
988 voe_wrapper_->file()->StopRecordingMicrophone();
989 monitor_.reset();
990 return false;
991 }
992 } else if (!enable && monitor_) {
993 voe_wrapper_->file()->StopRecordingMicrophone();
994 monitor_.reset();
995 }
996 return true;
997}
998
999bool WebRtcVoiceEngine::PauseLocalMonitor() {
1000 return ChangeLocalMonitor(false);
1001}
1002
1003bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1004 return ChangeLocalMonitor(desired_local_monitor_enable_);
1005}
1006
1007const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1008 return codecs_;
1009}
1010
1011bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1012 return FindWebRtcCodec(in, NULL);
1013}
1014
1015// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1016bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1017 webrtc::CodecInst* out) {
1018 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1019 for (int i = 0; i < ncodecs; ++i) {
1020 webrtc::CodecInst voe_codec;
1021 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1022 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1023 voe_codec.rate, voe_codec.channels, 0);
1024 bool multi_rate = IsCodecMultiRate(voe_codec);
1025 // Allow arbitrary rates for ISAC to be specified.
1026 if (multi_rate) {
1027 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1028 codec.bitrate = 0;
1029 }
1030 if (codec.Matches(in)) {
1031 if (out) {
1032 // Fixup the payload type.
1033 voe_codec.pltype = in.id;
1034
1035 // Set bitrate if specified.
1036 if (multi_rate && in.bitrate != 0) {
1037 voe_codec.rate = in.bitrate;
1038 }
1039
1040 // Apply codec-specific settings.
1041 if (IsIsac(codec)) {
1042 // If ISAC and an explicit bitrate is not specified,
1043 // enable auto bandwidth adjustment.
1044 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1045 }
1046 *out = voe_codec;
1047 }
1048 return true;
1049 }
1050 }
1051 }
1052 return false;
1053}
1054const std::vector<RtpHeaderExtension>&
1055WebRtcVoiceEngine::rtp_header_extensions() const {
1056 return rtp_header_extensions_;
1057}
1058
1059void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1060 // if min_sev == -1, we keep the current log level.
1061 if (min_sev >= 0) {
1062 SetTraceFilter(SeverityToFilter(min_sev));
1063 }
1064 log_options_ = filter;
1065 SetTraceOptions(initialized_ ? log_options_ : "");
1066}
1067
1068int WebRtcVoiceEngine::GetLastEngineError() {
1069 return voe_wrapper_->error();
1070}
1071
1072void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1073 log_filter_ = filter;
1074 tracing_->SetTraceFilter(filter);
1075}
1076
1077// We suppport three different logging settings for VoiceEngine:
1078// 1. Observer callback that goes into talk diagnostic logfile.
1079// Use --logfile and --loglevel
1080//
1081// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1082// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1083//
1084// 3. EC log and dump for debugging QualityEngine.
1085// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1086//
1087// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1088// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1089void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1090 // Set encrypted trace file.
1091 std::vector<std::string> opts;
1092 talk_base::tokenize(options, ' ', '"', '"', &opts);
1093 std::vector<std::string>::iterator tracefile =
1094 std::find(opts.begin(), opts.end(), "tracefile");
1095 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1096 // Write encrypted debug output (at same loglevel) to file
1097 // EncryptedTraceFile no longer supported.
1098 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1099 LOG_RTCERR1(SetTraceFile, *tracefile);
1100 }
1101 }
1102
1103 // Set AEC dump file
1104 std::vector<std::string>::iterator recordEC =
1105 std::find(opts.begin(), opts.end(), "recordEC");
1106 if (recordEC != opts.end()) {
1107 ++recordEC;
1108 if (recordEC != opts.end())
1109 StartAecDump(recordEC->c_str());
1110 else
1111 StopAecDump();
1112 }
1113}
1114
1115// Ignore spammy trace messages, mostly from the stats API when we haven't
1116// gotten RTCP info yet from the remote side.
1117bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1118 static const char* kTracesToIgnore[] = {
1119 "\tfailed to GetReportBlockInformation",
1120 "GetRecCodec() failed to get received codec",
1121 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1122 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1123 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1124 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1125 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1126 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1127 "SenderInfoReceived No received SR",
1128 "StatisticsRTP() no statistics available",
1129 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1130 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1131 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1132 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1133 NULL
1134 };
1135 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1136 if (trace.find(*p) != std::string::npos) {
1137 return true;
1138 }
1139 }
1140 return false;
1141}
1142
1143void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1144 int length) {
1145 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1146 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1147 sev = talk_base::LS_ERROR;
1148 else if (level == webrtc::kTraceWarning)
1149 sev = talk_base::LS_WARNING;
1150 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1151 sev = talk_base::LS_INFO;
1152 else if (level == webrtc::kTraceTerseInfo)
1153 sev = talk_base::LS_INFO;
1154
1155 // Skip past boilerplate prefix text
1156 if (length < 72) {
1157 std::string msg(trace, length);
1158 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1159 LOG_V(sev) << msg;
1160 } else {
1161 std::string msg(trace + 71, length - 72);
1162 if (!ShouldIgnoreTrace(msg)) {
1163 LOG_V(sev) << "webrtc: " << msg;
1164 }
1165 }
1166}
1167
1168void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1169 talk_base::CritScope lock(&channels_cs_);
1170 WebRtcVoiceMediaChannel* channel = NULL;
1171 uint32 ssrc = 0;
1172 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1173 << channel_num << ".";
1174 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1175 ASSERT(channel != NULL);
1176 channel->OnError(ssrc, err_code);
1177 } else {
1178 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1179 << " could not be found in channel list when error reported.";
1180 }
1181}
1182
1183bool WebRtcVoiceEngine::FindChannelAndSsrc(
1184 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1185 ASSERT(channel != NULL && ssrc != NULL);
1186
1187 *channel = NULL;
1188 *ssrc = 0;
1189 // Find corresponding channel and ssrc
1190 for (ChannelList::const_iterator it = channels_.begin();
1191 it != channels_.end(); ++it) {
1192 ASSERT(*it != NULL);
1193 if ((*it)->FindSsrc(channel_num, ssrc)) {
1194 *channel = *it;
1195 return true;
1196 }
1197 }
1198
1199 return false;
1200}
1201
1202// This method will search through the WebRtcVoiceMediaChannels and
1203// obtain the voice engine's channel number.
1204bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1205 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1206 ASSERT(channel_num != NULL);
1207 ASSERT(direction == MPD_RX || direction == MPD_TX);
1208
1209 *channel_num = -1;
1210 // Find corresponding channel for ssrc.
1211 for (ChannelList::const_iterator it = channels_.begin();
1212 it != channels_.end(); ++it) {
1213 ASSERT(*it != NULL);
1214 if (direction & MPD_RX) {
1215 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1216 }
1217 if (*channel_num == -1 && (direction & MPD_TX)) {
1218 *channel_num = (*it)->GetSendChannelNum(ssrc);
1219 }
1220 if (*channel_num != -1) {
1221 return true;
1222 }
1223 }
1224 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1225 return false;
1226}
1227
1228void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1229 talk_base::CritScope lock(&channels_cs_);
1230 channels_.push_back(channel);
1231}
1232
1233void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1234 talk_base::CritScope lock(&channels_cs_);
1235 ChannelList::iterator i = std::find(channels_.begin(),
1236 channels_.end(),
1237 channel);
1238 if (i != channels_.end()) {
1239 channels_.erase(i);
1240 }
1241}
1242
1243void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1244 soundclips_.push_back(soundclip);
1245}
1246
1247void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1248 SoundclipList::iterator i = std::find(soundclips_.begin(),
1249 soundclips_.end(),
1250 soundclip);
1251 if (i != soundclips_.end()) {
1252 soundclips_.erase(i);
1253 }
1254}
1255
1256// Adjusts the default AGC target level by the specified delta.
1257// NB: If we start messing with other config fields, we'll want
1258// to save the current webrtc::AgcConfig as well.
1259bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1260 webrtc::AgcConfig config = default_agc_config_;
1261 config.targetLeveldBOv -= delta;
1262
1263 LOG(LS_INFO) << "Adjusting AGC level from default -"
1264 << default_agc_config_.targetLeveldBOv << "dB to -"
1265 << config.targetLeveldBOv << "dB";
1266
1267 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1268 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1269 return false;
1270 }
1271 return true;
1272}
1273
1274bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1275 webrtc::AudioDeviceModule* adm_sc) {
1276 if (initialized_) {
1277 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1278 return false;
1279 }
1280 if (adm_) {
1281 adm_->Release();
1282 adm_ = NULL;
1283 }
1284 if (adm) {
1285 adm_ = adm;
1286 adm_->AddRef();
1287 }
1288
1289 if (adm_sc_) {
1290 adm_sc_->Release();
1291 adm_sc_ = NULL;
1292 }
1293 if (adm_sc) {
1294 adm_sc_ = adm_sc;
1295 adm_sc_->AddRef();
1296 }
1297 return true;
1298}
1299
1300bool WebRtcVoiceEngine::RegisterProcessor(
1301 uint32 ssrc,
1302 VoiceProcessor* voice_processor,
1303 MediaProcessorDirection direction) {
1304 bool register_with_webrtc = false;
1305 int channel_id = -1;
1306 bool success = false;
1307 uint32* processor_ssrc = NULL;
1308 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1309 if (voice_processor == NULL || !found_channel) {
1310 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1311 << " foundChannel: " << found_channel;
1312 return false;
1313 }
1314
1315 webrtc::ProcessingTypes processing_type;
1316 {
1317 talk_base::CritScope cs(&signal_media_critical_);
1318 if (direction == MPD_RX) {
1319 processing_type = webrtc::kPlaybackAllChannelsMixed;
1320 if (SignalRxMediaFrame.is_empty()) {
1321 register_with_webrtc = true;
1322 processor_ssrc = &rx_processor_ssrc_;
1323 }
1324 SignalRxMediaFrame.connect(voice_processor,
1325 &VoiceProcessor::OnFrame);
1326 } else {
1327 processing_type = webrtc::kRecordingPerChannel;
1328 if (SignalTxMediaFrame.is_empty()) {
1329 register_with_webrtc = true;
1330 processor_ssrc = &tx_processor_ssrc_;
1331 }
1332 SignalTxMediaFrame.connect(voice_processor,
1333 &VoiceProcessor::OnFrame);
1334 }
1335 }
1336 if (register_with_webrtc) {
1337 // TODO(janahan): when registering consider instantiating a
1338 // a VoeMediaProcess object and not make the engine extend the interface.
1339 if (voe()->media() && voe()->media()->
1340 RegisterExternalMediaProcessing(channel_id,
1341 processing_type,
1342 *this) != -1) {
1343 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1344 << channel_id;
1345 *processor_ssrc = ssrc;
1346 success = true;
1347 } else {
1348 LOG_RTCERR2(RegisterExternalMediaProcessing,
1349 channel_id,
1350 processing_type);
1351 success = false;
1352 }
1353 } else {
1354 // If we don't have to register with the engine, we just needed to
1355 // connect a new processor, set success to true;
1356 success = true;
1357 }
1358 return success;
1359}
1360
1361bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1362 MediaProcessorDirection channel_direction,
1363 uint32 ssrc,
1364 VoiceProcessor* voice_processor,
1365 MediaProcessorDirection processor_direction) {
1366 bool success = true;
1367 FrameSignal* signal;
1368 webrtc::ProcessingTypes processing_type;
1369 uint32* processor_ssrc = NULL;
1370 if (channel_direction == MPD_RX) {
1371 signal = &SignalRxMediaFrame;
1372 processing_type = webrtc::kPlaybackAllChannelsMixed;
1373 processor_ssrc = &rx_processor_ssrc_;
1374 } else {
1375 signal = &SignalTxMediaFrame;
1376 processing_type = webrtc::kRecordingPerChannel;
1377 processor_ssrc = &tx_processor_ssrc_;
1378 }
1379
1380 int deregister_id = -1;
1381 {
1382 talk_base::CritScope cs(&signal_media_critical_);
1383 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1384 signal->disconnect(voice_processor);
1385 int channel_id = -1;
1386 bool found_channel = FindChannelNumFromSsrc(ssrc,
1387 channel_direction,
1388 &channel_id);
1389 if (signal->is_empty() && found_channel) {
1390 deregister_id = channel_id;
1391 }
1392 }
1393 }
1394 if (deregister_id != -1) {
1395 if (voe()->media() &&
1396 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1397 processing_type) != -1) {
1398 *processor_ssrc = 0;
1399 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1400 << deregister_id;
1401 } else {
1402 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1403 deregister_id,
1404 processing_type);
1405 success = false;
1406 }
1407 }
1408 return success;
1409}
1410
1411bool WebRtcVoiceEngine::UnregisterProcessor(
1412 uint32 ssrc,
1413 VoiceProcessor* voice_processor,
1414 MediaProcessorDirection direction) {
1415 bool success = true;
1416 if (voice_processor == NULL) {
1417 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1418 << ssrc;
1419 return false;
1420 }
1421 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1422 success = false;
1423 }
1424 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1425 success = false;
1426 }
1427 return success;
1428}
1429
1430// Implementing method from WebRtc VoEMediaProcess interface
1431// Do not lock mux_channel_cs_ in this callback.
1432void WebRtcVoiceEngine::Process(int channel,
1433 webrtc::ProcessingTypes type,
1434 int16_t audio10ms[],
1435 int length,
1436 int sampling_freq,
1437 bool is_stereo) {
1438 talk_base::CritScope cs(&signal_media_critical_);
1439 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1440 if (type == webrtc::kPlaybackAllChannelsMixed) {
1441 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1442 } else if (type == webrtc::kRecordingPerChannel) {
1443 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1444 } else {
1445 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1446 << " channel: " << channel << " type: " << type
1447 << " tx_ssrc: " << tx_processor_ssrc_
1448 << " rx_ssrc: " << rx_processor_ssrc_;
1449 }
1450}
1451
1452void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1453 if (!is_dumping_aec_) {
1454 // Start dumping AEC when we are not dumping.
1455 if (voe_wrapper_->processing()->StartDebugRecording(
1456 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
1457 LOG_RTCERR0(StartDebugRecording);
1458 } else {
1459 is_dumping_aec_ = true;
1460 }
1461 }
1462}
1463
1464void WebRtcVoiceEngine::StopAecDump() {
1465 if (is_dumping_aec_) {
1466 // Stop dumping AEC when we are dumping.
1467 if (voe_wrapper_->processing()->StopDebugRecording() !=
1468 webrtc::AudioProcessing::kNoError) {
1469 LOG_RTCERR0(StopDebugRecording);
1470 }
1471 is_dumping_aec_ = false;
1472 }
1473}
1474
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001475// This struct relies on the generated copy constructor and assignment operator
1476// since it is used in an stl::map.
1477struct WebRtcVoiceMediaChannel::WebRtcVoiceChannelInfo {
1478 WebRtcVoiceChannelInfo() : channel(-1), renderer(NULL) {}
1479 WebRtcVoiceChannelInfo(int ch, AudioRenderer* r)
1480 : channel(ch),
1481 renderer(r) {}
1482 ~WebRtcVoiceChannelInfo() {}
1483
1484 int channel;
1485 AudioRenderer* renderer;
1486};
1487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488// WebRtcVoiceMediaChannel
1489WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1490 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1491 engine,
1492 engine->voe()->base()->CreateChannel()),
1493 options_(),
1494 dtmf_allowed_(false),
1495 desired_playout_(false),
1496 nack_enabled_(false),
1497 playout_(false),
1498 desired_send_(SEND_NOTHING),
1499 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500 default_receive_ssrc_(0) {
1501 engine->RegisterChannel(this);
1502 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1503 << voe_channel();
1504
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001505 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506}
1507
1508WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1509 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1510 << voe_channel();
1511
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001512 // Remove any remaining send streams, the default channel will be deleted
1513 // later.
1514 while (!send_channels_.empty())
1515 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001516
1517 // Unregister ourselves from the engine.
1518 engine()->UnregisterChannel(this);
1519 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001520 while (!receive_channels_.empty()) {
1521 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522 }
1523
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001524 // Delete the default channel.
1525 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526}
1527
1528bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1529 LOG(LS_INFO) << "Setting voice channel options: "
1530 << options.ToString();
1531
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001532 // TODO(xians): Add support to set different options for different send
1533 // streams after we support multiple APMs.
1534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535 // We retain all of the existing options, and apply the given ones
1536 // on top. This means there is no way to "clear" options such that
1537 // they go back to the engine default.
1538 options_.SetAll(options);
1539
1540 if (send_ != SEND_NOTHING) {
1541 if (!engine()->SetOptionOverrides(options_)) {
1542 LOG(LS_WARNING) <<
1543 "Failed to engine SetOptionOverrides during channel SetOptions.";
1544 return false;
1545 }
1546 } else {
1547 // Will be interpreted when appropriate.
1548 }
1549
1550 LOG(LS_INFO) << "Set voice channel options. Current options: "
1551 << options_.ToString();
1552 return true;
1553}
1554
1555bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1556 const std::vector<AudioCodec>& codecs) {
1557 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 LOG(LS_INFO) << "Setting receive voice codecs:";
1559
1560 std::vector<AudioCodec> new_codecs;
1561 // Find all new codecs. We allow adding new codecs but don't allow changing
1562 // the payload type of codecs that is already configured since we might
1563 // already be receiving packets with that payload type.
1564 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001565 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 AudioCodec old_codec;
1567 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1568 if (old_codec.id != it->id) {
1569 LOG(LS_ERROR) << it->name << " payload type changed.";
1570 return false;
1571 }
1572 } else {
1573 new_codecs.push_back(*it);
1574 }
1575 }
1576 if (new_codecs.empty()) {
1577 // There are no new codecs to configure. Already configured codecs are
1578 // never removed.
1579 return true;
1580 }
1581
1582 if (playout_) {
1583 // Receive codecs can not be changed while playing. So we temporarily
1584 // pause playout.
1585 PausePlayout();
1586 }
1587
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001588 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001589 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1590 it != new_codecs.end() && ret; ++it) {
1591 webrtc::CodecInst voe_codec;
1592 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1593 LOG(LS_INFO) << ToString(*it);
1594 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001595 if (default_receive_ssrc_ == 0) {
1596 // Set the receive codecs on the default channel explicitly if the
1597 // default channel is not used by |receive_channels_|, this happens in
1598 // conference mode or in non-conference mode when there is no playout
1599 // channel.
1600 // TODO(xians): Figure out how we use the default channel in conference
1601 // mode.
1602 if (engine()->voe()->codec()->SetRecPayloadType(
1603 voe_channel(), voe_codec) == -1) {
1604 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1605 ret = false;
1606 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 }
1608
1609 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001610 for (ChannelMap::iterator it = receive_channels_.begin();
1611 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612 if (engine()->voe()->codec()->SetRecPayloadType(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001613 it->second.channel, voe_codec) == -1) {
1614 LOG_RTCERR2(SetRecPayloadType, it->second.channel,
1615 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616 ret = false;
1617 }
1618 }
1619 } else {
1620 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1621 ret = false;
1622 }
1623 }
1624 if (ret) {
1625 recv_codecs_ = codecs;
1626 }
1627
1628 if (desired_playout_ && !playout_) {
1629 ResumePlayout();
1630 }
1631 return ret;
1632}
1633
1634bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001635 int channel, const std::vector<AudioCodec>& codecs) {
1636 // Disable VAD, and FEC unless we know the other side wants them.
1637 engine()->voe()->codec()->SetVADStatus(channel, false);
1638 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1639 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640
1641 // Scan through the list to figure out the codec to use for sending, along
1642 // with the proper configuration for VAD and DTMF.
1643 bool first = true;
1644 webrtc::CodecInst send_codec;
1645 memset(&send_codec, 0, sizeof(send_codec));
1646
1647 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1648 it != codecs.end(); ++it) {
1649 // Ignore codecs we don't know about. The negotiation step should prevent
1650 // this, but double-check to be sure.
1651 webrtc::CodecInst voe_codec;
1652 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
1653 LOG(LS_WARNING) << "Unknown codec " << ToString(voe_codec);
1654 continue;
1655 }
1656
1657 // If OPUS, change what we send according to the "stereo" codec
1658 // parameter, and not the "channels" parameter. We set
1659 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1660 // the bitrate is not specified, i.e. is zero, we set it to the
1661 // appropriate default value for mono or stereo Opus.
1662 if (IsOpus(*it)) {
1663 if (IsOpusStereoEnabled(*it)) {
1664 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001665 if (!IsValidOpusBitrate(it->bitrate)) {
1666 if (it->bitrate != 0) {
1667 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1668 << it->bitrate
1669 << ") with default opus stereo bitrate: "
1670 << kOpusStereoBitrate;
1671 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672 voe_codec.rate = kOpusStereoBitrate;
1673 }
1674 } else {
1675 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001676 if (!IsValidOpusBitrate(it->bitrate)) {
1677 if (it->bitrate != 0) {
1678 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1679 << it->bitrate
1680 << ") with default opus mono bitrate: "
1681 << kOpusMonoBitrate;
1682 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 voe_codec.rate = kOpusMonoBitrate;
1684 }
1685 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001686 int bitrate_from_params = GetOpusBitrateFromParams(*it);
1687 if (bitrate_from_params != 0) {
1688 voe_codec.rate = bitrate_from_params;
1689 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 }
1691
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001692 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1693 // about it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1695 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001696 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
1697 channel, it->id) == -1) {
1698 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
1699 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 }
1702
1703 // Turn voice activity detection/comfort noise on if supported.
1704 // Set the wideband CN payload type appropriately.
1705 // (narrowband always uses the static payload type 13).
1706 if (_stricmp(it->name.c_str(), "CN") == 0) {
1707 webrtc::PayloadFrequencies cn_freq;
1708 switch (it->clockrate) {
1709 case 8000:
1710 cn_freq = webrtc::kFreq8000Hz;
1711 break;
1712 case 16000:
1713 cn_freq = webrtc::kFreq16000Hz;
1714 break;
1715 case 32000:
1716 cn_freq = webrtc::kFreq32000Hz;
1717 break;
1718 default:
1719 LOG(LS_WARNING) << "CN frequency " << it->clockrate
1720 << " not supported.";
1721 continue;
1722 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001723 // Set the CN payloadtype and the VAD status.
1724 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1725 if (cn_freq != webrtc::kFreq8000Hz) {
1726 if (engine()->voe()->codec()->SetSendCNPayloadType(
1727 channel, it->id, cn_freq) == -1) {
1728 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
1729 // TODO(ajm): This failure condition will be removed from VoE.
1730 // Restore the return here when we update to a new enough webrtc.
1731 //
1732 // Not returning false because the SetSendCNPayloadType will fail if
1733 // the channel is already sending.
1734 // This can happen if the remote description is applied twice, for
1735 // example in the case of ROAP on top of JSEP, where both side will
1736 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001737 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001738 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001739
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001740 // Only turn on VAD if we have a CN payload type that matches the
1741 // clockrate for the codec we are going to use.
1742 if (it->clockrate == send_codec.plfreq) {
1743 LOG(LS_INFO) << "Enabling VAD";
1744 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1745 LOG_RTCERR2(SetVADStatus, channel, true);
1746 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747 }
1748 }
1749 }
1750
1751 // We'll use the first codec in the list to actually send audio data.
1752 // Be sure to use the payload type requested by the remote side.
1753 // "red", for FEC audio, is a special case where the actual codec to be
1754 // used is specified in params.
1755 if (first) {
1756 if (_stricmp(it->name.c_str(), "red") == 0) {
1757 // Parse out the RED parameters. If we fail, just ignore RED;
1758 // we don't support all possible params/usage scenarios.
1759 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1760 continue;
1761 }
1762
1763 // Enable redundant encoding of the specified codec. Treat any
1764 // failure as a fatal internal error.
1765 LOG(LS_INFO) << "Enabling FEC";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001766 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
1767 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
1768 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 }
1770 } else {
1771 send_codec = voe_codec;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001772 nack_enabled_ = IsNackEnabled(*it);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001773 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 }
1775 first = false;
1776 // Set the codec immediately, since SetVADStatus() depends on whether
1777 // the current codec is mono or stereo.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001778 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779 return false;
1780 }
1781 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001782
1783 // If we're being asked to set an empty list of codecs, due to a buggy client,
1784 // choose the most common format: PCMU
1785 if (first) {
1786 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
1787 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
1788 engine()->FindWebRtcCodec(codec, &send_codec);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001789 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790 return false;
1791 }
1792
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001793 // Always update the |send_codec_| to the currently set send codec.
1794 send_codec_.reset(new webrtc::CodecInst(send_codec));
1795
1796 return true;
1797}
1798
1799bool WebRtcVoiceMediaChannel::SetSendCodecs(
1800 const std::vector<AudioCodec>& codecs) {
1801 dtmf_allowed_ = false;
1802 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1803 it != codecs.end(); ++it) {
1804 // Find the DTMF telephone event "codec".
1805 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1806 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
1807 dtmf_allowed_ = true;
1808 }
1809 }
1810
1811 // Cache the codecs in order to configure the channel created later.
1812 send_codecs_ = codecs;
1813 for (ChannelMap::iterator iter = send_channels_.begin();
1814 iter != send_channels_.end(); ++iter) {
1815 if (!SetSendCodecs(iter->second.channel, codecs)) {
1816 return false;
1817 }
1818 }
1819
1820 SetNack(receive_channels_, nack_enabled_);
1821
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 return true;
1823}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001824
1825void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
1826 bool nack_enabled) {
1827 for (ChannelMap::const_iterator it = channels.begin();
1828 it != channels.end(); ++it) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001829 SetNack(it->second.channel, nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001830 }
1831}
1832
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001833void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001835 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001836 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1837 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001838 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1840 }
1841}
1842
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843bool WebRtcVoiceMediaChannel::SetSendCodec(
1844 const webrtc::CodecInst& send_codec) {
1845 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
1846 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001847 for (ChannelMap::iterator iter = send_channels_.begin();
1848 iter != send_channels_.end(); ++iter) {
1849 if (!SetSendCodec(iter->second.channel, send_codec))
1850 return false;
1851 }
1852
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001853 return true;
1854}
1855
1856bool WebRtcVoiceMediaChannel::SetSendCodec(
1857 int channel, const webrtc::CodecInst& send_codec) {
1858 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1859 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1860
1861 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1862 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001863 return false;
1864 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 return true;
1866}
1867
1868bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
1869 const std::vector<RtpHeaderExtension>& extensions) {
1870 // We don't support any incoming extensions headers right now.
1871 return true;
1872}
1873
1874bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
1875 const std::vector<RtpHeaderExtension>& extensions) {
1876 // Enable the audio level extension header if requested.
1877 std::vector<RtpHeaderExtension>::const_iterator it;
1878 for (it = extensions.begin(); it != extensions.end(); ++it) {
1879 if (it->uri == kRtpAudioLevelHeaderExtension) {
1880 break;
1881 }
1882 }
1883
1884 bool enable = (it != extensions.end());
1885 int id = 0;
1886
1887 if (enable) {
1888 id = it->id;
1889 if (id < kMinRtpHeaderExtensionId ||
1890 id > kMaxRtpHeaderExtensionId) {
1891 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
1892 return false;
1893 }
1894 }
1895
1896 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001897 for (ChannelMap::const_iterator iter = send_channels_.begin();
1898 iter != send_channels_.end(); ++iter) {
1899 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
1900 iter->second.channel, enable, id) == -1) {
1901 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
1902 iter->second.channel, enable, id);
1903 return false;
1904 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 }
1906
1907 return true;
1908}
1909
1910bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1911 desired_playout_ = playout;
1912 return ChangePlayout(desired_playout_);
1913}
1914
1915bool WebRtcVoiceMediaChannel::PausePlayout() {
1916 return ChangePlayout(false);
1917}
1918
1919bool WebRtcVoiceMediaChannel::ResumePlayout() {
1920 return ChangePlayout(desired_playout_);
1921}
1922
1923bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
1924 if (playout_ == playout) {
1925 return true;
1926 }
1927
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001928 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001930 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 // Only toggle the default channel if we don't have any other channels.
1932 result = SetPlayout(voe_channel(), playout);
1933 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001934 for (ChannelMap::iterator it = receive_channels_.begin();
1935 it != receive_channels_.end() && result; ++it) {
1936 if (!SetPlayout(it->second.channel, playout)) {
1937 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
1938 << it->second.channel << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939 result = false;
1940 }
1941 }
1942
1943 if (result) {
1944 playout_ = playout;
1945 }
1946 return result;
1947}
1948
1949bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
1950 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001951 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 return ChangeSend(desired_send_);
1953 return true;
1954}
1955
1956bool WebRtcVoiceMediaChannel::PauseSend() {
1957 return ChangeSend(SEND_NOTHING);
1958}
1959
1960bool WebRtcVoiceMediaChannel::ResumeSend() {
1961 return ChangeSend(desired_send_);
1962}
1963
1964bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
1965 if (send_ == send) {
1966 return true;
1967 }
1968
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001969 // Change the settings on each send channel.
1970 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971 engine()->SetOptionOverrides(options_);
1972
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001973 // Change the settings on each send channel.
1974 for (ChannelMap::iterator iter = send_channels_.begin();
1975 iter != send_channels_.end(); ++iter) {
1976 if (!ChangeSend(iter->second.channel, send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001979
1980 // Clear up the options after stopping sending.
1981 if (send == SEND_NOTHING)
1982 engine()->ClearOptionOverrides();
1983
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 send_ = send;
1985 return true;
1986}
1987
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001988bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
1989 if (send == SEND_MICROPHONE) {
1990 if (engine()->voe()->base()->StartSend(channel) == -1) {
1991 LOG_RTCERR1(StartSend, channel);
1992 return false;
1993 }
1994 if (engine()->voe()->file() &&
1995 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
1996 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
1997 return false;
1998 }
1999 } else { // SEND_NOTHING
2000 ASSERT(send == SEND_NOTHING);
2001 if (engine()->voe()->base()->StopSend(channel) == -1) {
2002 LOG_RTCERR1(StopSend, channel);
2003 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 }
2005 }
2006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 return true;
2008}
2009
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002010void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2011 if (engine()->voe()->network()->RegisterExternalTransport(
2012 channel, *this) == -1) {
2013 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2014 }
2015
2016 // Enable RTCP (for quality stats and feedback messages)
2017 EnableRtcp(channel);
2018
2019 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2020 ResetRecvCodecs(channel);
2021}
2022
2023bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2024 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2025 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2026 }
2027
2028 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2029 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 return false;
2031 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002032
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002033 return true;
2034}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002035
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002036bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2037 // If the default channel is already used for sending create a new channel
2038 // otherwise use the default channel for sending.
2039 int channel = GetSendChannelNum(sp.first_ssrc());
2040 if (channel != -1) {
2041 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2042 return false;
2043 }
2044
2045 bool default_channel_is_available = true;
2046 for (ChannelMap::const_iterator iter = send_channels_.begin();
2047 iter != send_channels_.end(); ++iter) {
2048 if (IsDefaultChannel(iter->second.channel)) {
2049 default_channel_is_available = false;
2050 break;
2051 }
2052 }
2053 if (default_channel_is_available) {
2054 channel = voe_channel();
2055 } else {
2056 // Create a new channel for sending audio data.
2057 channel = engine()->voe()->base()->CreateChannel();
2058 if (channel == -1) {
2059 LOG_RTCERR0(CreateChannel);
2060 return false;
2061 }
2062
2063 ConfigureSendChannel(channel);
2064 }
2065
2066 // Save the channel to send_channels_, so that RemoveSendStream() can still
2067 // delete the channel in case failure happens below.
2068 send_channels_[sp.first_ssrc()] = WebRtcVoiceChannelInfo(channel, NULL);
2069
2070 // Set the send (local) SSRC.
2071 // If there are multiple send SSRCs, we can only set the first one here, and
2072 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2073 // (with a codec requires multiple SSRC(s)).
2074 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2075 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2076 return false;
2077 }
2078
2079 // At this point the channel's local SSRC has been updated. If the channel is
2080 // the default channel make sure that all the receive channels are updated as
2081 // well. Receive channels have to have the same SSRC as the default channel in
2082 // order to send receiver reports with this SSRC.
2083 if (IsDefaultChannel(channel)) {
2084 for (ChannelMap::const_iterator it = receive_channels_.begin();
2085 it != receive_channels_.end(); ++it) {
2086 // Only update the SSRC for non-default channels.
2087 if (!IsDefaultChannel(it->second.channel)) {
2088 if (engine()->voe()->rtp()->SetLocalSSRC(it->second.channel,
2089 sp.first_ssrc()) != 0) {
2090 LOG_RTCERR2(SetLocalSSRC, it->second.channel, sp.first_ssrc());
2091 return false;
2092 }
2093 }
2094 }
2095 }
2096
2097 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2098 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2099 return false;
2100 }
2101
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002102 // Set the current codecs to be used for the new channel.
2103 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002104 return false;
2105
2106 return ChangeSend(channel, desired_send_);
2107}
2108
2109bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2110 ChannelMap::iterator it = send_channels_.find(ssrc);
2111 if (it == send_channels_.end()) {
2112 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2113 << " which doesn't exist.";
2114 return false;
2115 }
2116
2117 int channel = it->second.channel;
2118 ChangeSend(channel, SEND_NOTHING);
2119
2120 // Notify the audio renderer that the send channel is going away.
2121 if (it->second.renderer)
2122 it->second.renderer->RemoveChannel(channel);
2123
2124 if (IsDefaultChannel(channel)) {
2125 // Do not delete the default channel since the receive channels depend on
2126 // the default channel, recycle it instead.
2127 ChangeSend(channel, SEND_NOTHING);
2128 } else {
2129 // Clean up and delete the send channel.
2130 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2131 << " with VoiceEngine channel #" << channel << ".";
2132 if (!DeleteChannel(channel))
2133 return false;
2134 }
2135
2136 send_channels_.erase(it);
2137 if (send_channels_.empty())
2138 ChangeSend(SEND_NOTHING);
2139
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 return true;
2141}
2142
2143bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002144 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145
2146 if (!VERIFY(sp.ssrcs.size() == 1))
2147 return false;
2148 uint32 ssrc = sp.first_ssrc();
2149
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002150 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2151 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152 return false;
2153 }
2154
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002155 // Reuse default channel for recv stream in non-conference mode call
2156 // when the default channel is not being used.
2157 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2158 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2159 << " reuse default channel";
2160 default_receive_ssrc_ = sp.first_ssrc();
2161 receive_channels_.insert(std::make_pair(
2162 default_receive_ssrc_, WebRtcVoiceChannelInfo(voe_channel(), NULL)));
2163 return SetPlayout(voe_channel(), playout_);
2164 }
2165
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 // Create a new channel for receiving audio data.
2167 int channel = engine()->voe()->base()->CreateChannel();
2168 if (channel == -1) {
2169 LOG_RTCERR0(CreateChannel);
2170 return false;
2171 }
2172
2173 // Configure to use external transport, like our default channel.
2174 if (engine()->voe()->network()->RegisterExternalTransport(
2175 channel, *this) == -1) {
2176 LOG_RTCERR2(SetExternalTransport, channel, this);
2177 return false;
2178 }
2179
2180 // Use the same SSRC as our default channel (so the RTCP reports are correct).
2181 unsigned int send_ssrc;
2182 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2183 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
2184 LOG_RTCERR2(GetSendSSRC, channel, send_ssrc);
2185 return false;
2186 }
2187 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
2188 LOG_RTCERR2(SetSendSSRC, channel, send_ssrc);
2189 return false;
2190 }
2191
2192 // Use the same recv payload types as our default channel.
2193 ResetRecvCodecs(channel);
2194 if (!recv_codecs_.empty()) {
2195 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2196 it != recv_codecs_.end(); ++it) {
2197 webrtc::CodecInst voe_codec;
2198 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2199 voe_codec.pltype = it->id;
2200 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2201 if (engine()->voe()->codec()->GetRecPayloadType(
2202 voe_channel(), voe_codec) != -1) {
2203 if (engine()->voe()->codec()->SetRecPayloadType(
2204 channel, voe_codec) == -1) {
2205 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2206 return false;
2207 }
2208 }
2209 }
2210 }
2211 }
2212
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002213 if (InConferenceMode()) {
2214 // To be in par with the video, voe_channel() is not used for receiving in
2215 // a conference call.
2216 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2217 // This is the first stream in a multi user meeting. We can now
2218 // disable playback of the default stream. This since the default
2219 // stream will probably have received some initial packets before
2220 // the new stream was added. This will mean that the CN state from
2221 // the default channel will be mixed in with the other streams
2222 // throughout the whole meeting, which might be disturbing.
2223 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2224 SetPlayout(voe_channel(), false);
2225 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002227 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002229 receive_channels_.insert(
2230 std::make_pair(ssrc, WebRtcVoiceChannelInfo(channel, NULL)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231
2232 // TODO(juberti): We should rollback the add if SetPlayout fails.
2233 LOG(LS_INFO) << "New audio stream " << ssrc
2234 << " registered to VoiceEngine channel #"
2235 << channel << ".";
2236 return SetPlayout(channel, playout_);
2237}
2238
2239bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002240 talk_base::CritScope lock(&receive_channels_cs_);
2241 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002242 if (it == receive_channels_.end()) {
2243 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2244 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002245 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002246 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002248 if (ssrc == default_receive_ssrc_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002249 ASSERT(IsDefaultChannel(it->second.channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002250 // Recycle the default channel is for recv stream.
2251 if (playout_)
2252 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002254 if (it->second.renderer)
2255 it->second.renderer->RemoveChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002257 default_receive_ssrc_ = 0;
2258 receive_channels_.erase(it);
2259 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002260 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002261
2262 // Non default channel.
2263 // Notify the renderer that channel is going away.
2264 if (it->second.renderer)
2265 it->second.renderer->RemoveChannel(it->second.channel);
2266
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002267 LOG(LS_INFO) << "Removing audio stream " << ssrc
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002268 << " with VoiceEngine channel #" << it->second.channel << ".";
2269 if (!DeleteChannel(it->second.channel)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002270 // Erase the entry anyhow.
2271 receive_channels_.erase(it);
2272 return false;
2273 }
2274
2275 receive_channels_.erase(it);
2276 bool enable_default_channel_playout = false;
2277 if (receive_channels_.empty()) {
2278 // The last stream was removed. We can now enable the default
2279 // channel for new channels to be played out immediately without
2280 // waiting for AddStream messages.
2281 // We do this for both conference mode and non-conference mode.
2282 // TODO(oja): Does the default channel still have it's CN state?
2283 enable_default_channel_playout = true;
2284 }
2285 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2286 default_receive_ssrc_ != 0) {
2287 // Only the default channel is active, enable the playout on default
2288 // channel.
2289 enable_default_channel_playout = true;
2290 }
2291 if (enable_default_channel_playout && playout_) {
2292 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2293 SetPlayout(voe_channel(), true);
2294 }
2295
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002296 return true;
2297}
2298
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002299bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2300 AudioRenderer* renderer) {
2301 ChannelMap::iterator it = receive_channels_.find(ssrc);
2302 if (it == receive_channels_.end()) {
2303 if (renderer) {
2304 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002305 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002306 return false;
2307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002309 // The channel likely has gone away, do nothing.
2310 return true;
2311 }
2312
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002313 AudioRenderer* remote_renderer = it->second.renderer;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002314 if (renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002315 ASSERT(remote_renderer == NULL || remote_renderer == renderer);
2316 if (!remote_renderer) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002317 renderer->AddChannel(it->second.channel);
2318 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002319 } else if (remote_renderer) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002320 // |renderer| == NULL, remove the channel from the renderer.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002321 remote_renderer->RemoveChannel(it->second.channel);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002322 }
2323
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324 // Assign the new value to the struct.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002325 it->second.renderer = renderer;
2326 return true;
2327}
2328
2329bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2330 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002331 ChannelMap::iterator it = send_channels_.find(ssrc);
2332 if (it == send_channels_.end()) {
2333 if (renderer) {
2334 // Return an error if trying to set a valid renderer with an invalid ssrc.
2335 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2336 return false;
2337 }
2338
2339 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002340 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002341 }
2342
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002343 AudioRenderer* local_renderer = it->second.renderer;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002344 if (renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002345 ASSERT(local_renderer == NULL || local_renderer == renderer);
2346 if (!local_renderer)
2347 renderer->AddChannel(it->second.channel);
2348 } else if (local_renderer) {
2349 local_renderer->RemoveChannel(it->second.channel);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002350 }
2351
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002352 // Assign the new value to the struct.
2353 it->second.renderer = renderer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354 return true;
2355}
2356
2357bool WebRtcVoiceMediaChannel::GetActiveStreams(
2358 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002359 // In conference mode, the default channel should not be in
2360 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002361 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002362 for (ChannelMap::iterator it = receive_channels_.begin();
2363 it != receive_channels_.end(); ++it) {
2364 int level = GetOutputLevel(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002365 if (level > 0) {
2366 actives->push_back(std::make_pair(it->first, level));
2367 }
2368 }
2369 return true;
2370}
2371
2372int WebRtcVoiceMediaChannel::GetOutputLevel() {
2373 // return the highest output level of all streams
2374 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002375 for (ChannelMap::iterator it = receive_channels_.begin();
2376 it != receive_channels_.end(); ++it) {
2377 int level = GetOutputLevel(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 highest = talk_base::_max(level, highest);
2379 }
2380 return highest;
2381}
2382
2383int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2384 int ret;
2385 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2386 // In case of error, log the info and continue
2387 LOG_RTCERR0(TimeSinceLastTyping);
2388 ret = -1;
2389 } else {
2390 ret *= 1000; // We return ms, webrtc returns seconds.
2391 }
2392 return ret;
2393}
2394
2395void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2396 int cost_per_typing, int reporting_threshold, int penalty_decay,
2397 int type_event_delay) {
2398 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2399 time_window, cost_per_typing,
2400 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2401 // In case of error, log the info and continue
2402 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2403 cost_per_typing, reporting_threshold, penalty_decay,
2404 type_event_delay);
2405 }
2406}
2407
2408bool WebRtcVoiceMediaChannel::SetOutputScaling(
2409 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002410 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 // Collect the channels to scale the output volume.
2412 std::vector<int> channels;
2413 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002414 // Default channel is not in receive_channels_ if it is not being used for
2415 // playout.
2416 if (default_receive_ssrc_ == 0)
2417 channels.push_back(voe_channel());
2418 for (ChannelMap::const_iterator it = receive_channels_.begin();
2419 it != receive_channels_.end(); ++it) {
2420 channels.push_back(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002421 }
2422 } else { // Collect only the channel of the specified ssrc.
2423 int channel = GetReceiveChannelNum(ssrc);
2424 if (-1 == channel) {
2425 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2426 return false;
2427 }
2428 channels.push_back(channel);
2429 }
2430
2431 // Scale the output volume for the collected channels. We first normalize to
2432 // scale the volume and then set the left and right pan.
2433 float scale = static_cast<float>(talk_base::_max(left, right));
2434 if (scale > 0.0001f) {
2435 left /= scale;
2436 right /= scale;
2437 }
2438 for (std::vector<int>::const_iterator it = channels.begin();
2439 it != channels.end(); ++it) {
2440 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2441 *it, scale)) {
2442 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2443 return false;
2444 }
2445 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2446 *it, static_cast<float>(left), static_cast<float>(right))) {
2447 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2448 // Do not return if fails. SetOutputVolumePan is not available for all
2449 // pltforms.
2450 }
2451 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2452 << " right=" << right * scale
2453 << " for channel " << *it << " and ssrc " << ssrc;
2454 }
2455 return true;
2456}
2457
2458bool WebRtcVoiceMediaChannel::GetOutputScaling(
2459 uint32 ssrc, double* left, double* right) {
2460 if (!left || !right) return false;
2461
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002462 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 // Determine which channel based on ssrc.
2464 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2465 if (channel == -1) {
2466 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2467 return false;
2468 }
2469
2470 float scaling;
2471 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2472 channel, scaling)) {
2473 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2474 return false;
2475 }
2476
2477 float left_pan;
2478 float right_pan;
2479 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2480 channel, left_pan, right_pan)) {
2481 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2482 // If GetOutputVolumePan fails, we use the default left and right pan.
2483 left_pan = 1.0f;
2484 right_pan = 1.0f;
2485 }
2486
2487 *left = scaling * left_pan;
2488 *right = scaling * right_pan;
2489 return true;
2490}
2491
2492bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2493 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2494 return true;
2495}
2496
2497bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2498 bool play, bool loop) {
2499 if (!ringback_tone_) {
2500 return false;
2501 }
2502
2503 // The voe file api is not available in chrome.
2504 if (!engine()->voe()->file()) {
2505 return false;
2506 }
2507
2508 // Determine which VoiceEngine channel to play on.
2509 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2510 if (channel == -1) {
2511 return false;
2512 }
2513
2514 // Make sure the ringtone is cued properly, and play it out.
2515 if (play) {
2516 ringback_tone_->set_loop(loop);
2517 ringback_tone_->Rewind();
2518 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2519 ringback_tone_.get()) == -1) {
2520 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2521 LOG(LS_ERROR) << "Unable to start ringback tone";
2522 return false;
2523 }
2524 ringback_channels_.insert(channel);
2525 LOG(LS_INFO) << "Started ringback on channel " << channel;
2526 } else {
2527 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2528 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2529 LOG_RTCERR1(StopPlayingFileLocally, channel);
2530 return false;
2531 }
2532 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2533 ringback_channels_.erase(channel);
2534 }
2535
2536 return true;
2537}
2538
2539bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2540 return dtmf_allowed_;
2541}
2542
2543bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2544 int duration, int flags) {
2545 if (!dtmf_allowed_) {
2546 return false;
2547 }
2548
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 // Send the event.
2550 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002551 int channel = -1;
2552 if (ssrc == 0) {
2553 bool default_channel_is_inuse = false;
2554 for (ChannelMap::const_iterator iter = send_channels_.begin();
2555 iter != send_channels_.end(); ++iter) {
2556 if (IsDefaultChannel(iter->second.channel)) {
2557 default_channel_is_inuse = true;
2558 break;
2559 }
2560 }
2561 if (default_channel_is_inuse) {
2562 channel = voe_channel();
2563 } else if (!send_channels_.empty()) {
2564 channel = send_channels_.begin()->second.channel;
2565 }
2566 } else {
2567 channel = GetSendChannelNum(ssrc);
2568 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002569 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2571 << ssrc << " is not in use.";
2572 return false;
2573 }
2574 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002575 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2576 channel, event, true, duration) == -1) {
2577 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 return false;
2579 }
2580 }
2581
2582 // Play the event.
2583 if (flags & cricket::DF_PLAY) {
2584 // Play DTMF tone locally.
2585 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2586 LOG_RTCERR2(PlayDtmfTone, event, duration);
2587 return false;
2588 }
2589 }
2590
2591 return true;
2592}
2593
2594void WebRtcVoiceMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
2595 // Pick which channel to send this packet to. If this packet doesn't match
2596 // any multiplexed streams, just send it to the default channel. Otherwise,
2597 // send it to the specific decoder instance for that stream.
2598 int which_channel = GetReceiveChannelNum(
2599 ParseSsrc(packet->data(), packet->length(), false));
2600 if (which_channel == -1) {
2601 which_channel = voe_channel();
2602 }
2603
2604 // Stop any ringback that might be playing on the channel.
2605 // It's possible the ringback has already stopped, ih which case we'll just
2606 // use the opportunity to remove the channel from ringback_channels_.
2607 if (engine()->voe()->file()) {
2608 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2609 if (it != ringback_channels_.end()) {
2610 if (engine()->voe()->file()->IsPlayingFileLocally(
2611 which_channel) == 1) {
2612 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2613 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2614 << " due to incoming media";
2615 }
2616 ringback_channels_.erase(which_channel);
2617 }
2618 }
2619
2620 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002621 engine()->voe()->network()->ReceivedRTPPacket(
2622 which_channel,
2623 packet->data(),
2624 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002625}
2626
2627void WebRtcVoiceMediaChannel::OnRtcpReceived(talk_base::Buffer* packet) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002628 // Sending channels need all RTCP packets with feedback information.
2629 // Even sender reports can contain attached report blocks.
2630 // Receiving channels need sender reports in order to create
2631 // correct receiver reports.
2632 int type = 0;
2633 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2634 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2635 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 }
2637
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002638 // If it is a sender report, find the channel that is listening.
2639 bool has_sent_to_default_channel = false;
2640 if (type == kRtcpTypeSR) {
2641 int which_channel = GetReceiveChannelNum(
2642 ParseSsrc(packet->data(), packet->length(), true));
2643 if (which_channel != -1) {
2644 engine()->voe()->network()->ReceivedRTCPPacket(
2645 which_channel,
2646 packet->data(),
2647 static_cast<unsigned int>(packet->length()));
2648
2649 if (IsDefaultChannel(which_channel))
2650 has_sent_to_default_channel = true;
2651 }
2652 }
2653
2654 // SR may continue RR and any RR entry may correspond to any one of the send
2655 // channels. So all RTCP packets must be forwarded all send channels. VoE
2656 // will filter out RR internally.
2657 for (ChannelMap::iterator iter = send_channels_.begin();
2658 iter != send_channels_.end(); ++iter) {
2659 // Make sure not sending the same packet to default channel more than once.
2660 if (IsDefaultChannel(iter->second.channel) && has_sent_to_default_channel)
2661 continue;
2662
2663 engine()->voe()->network()->ReceivedRTCPPacket(
2664 iter->second.channel,
2665 packet->data(),
2666 static_cast<unsigned int>(packet->length()));
2667 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002668}
2669
2670bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002671 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2672 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2674 return false;
2675 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002676 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2677 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002678 return false;
2679 }
2680 return true;
2681}
2682
2683bool WebRtcVoiceMediaChannel::SetSendBandwidth(bool autobw, int bps) {
2684 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
2685
2686 if (!send_codec_) {
2687 LOG(LS_INFO) << "The send codec has not been set up yet.";
2688 return false;
2689 }
2690
2691 // Bandwidth is auto by default.
2692 if (autobw || bps <= 0)
2693 return true;
2694
2695 webrtc::CodecInst codec = *send_codec_;
2696 bool is_multi_rate = IsCodecMultiRate(codec);
2697
2698 if (is_multi_rate) {
2699 // If codec is multi-rate then just set the bitrate.
2700 codec.rate = bps;
2701 if (!SetSendCodec(codec)) {
2702 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2703 << " to bitrate " << bps << " bps.";
2704 return false;
2705 }
2706 return true;
2707 } else {
2708 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2709 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2710 // fixed bitrate then ignore.
2711 if (bps < codec.rate) {
2712 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2713 << " to bitrate " << bps << " bps"
2714 << ", requires at least " << codec.rate << " bps.";
2715 return false;
2716 }
2717 return true;
2718 }
2719}
2720
2721bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002722 bool echo_metrics_on = false;
2723 // These can take on valid negative values, so use the lowest possible level
2724 // as default rather than -1.
2725 int echo_return_loss = -100;
2726 int echo_return_loss_enhancement = -100;
2727 // These can also be negative, but in practice -1 is only used to signal
2728 // insufficient data, since the resolution is limited to multiples of 4 ms.
2729 int echo_delay_median_ms = -1;
2730 int echo_delay_std_ms = -1;
2731 if (engine()->voe()->processing()->GetEcMetricsStatus(
2732 echo_metrics_on) != -1 && echo_metrics_on) {
2733 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
2734 // here, but it appears to be unsuitable currently. Revisit after this is
2735 // investigated: http://b/issue?id=5666755
2736 int erl, erle, rerl, anlp;
2737 if (engine()->voe()->processing()->GetEchoMetrics(
2738 erl, erle, rerl, anlp) != -1) {
2739 echo_return_loss = erl;
2740 echo_return_loss_enhancement = erle;
2741 }
2742
2743 int median, std;
2744 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
2745 echo_delay_median_ms = median;
2746 echo_delay_std_ms = std;
2747 }
2748 }
2749
2750
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002751 webrtc::CallStatistics cs;
2752 unsigned int ssrc;
2753 webrtc::CodecInst codec;
2754 unsigned int level;
2755
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002756 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
2757 channel_iter != send_channels_.end(); ++channel_iter) {
2758 const int channel = channel_iter->second.channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002759
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002760 // Fill in the sender info, based on what we know, and what the
2761 // remote side told us it got from its RTCP report.
2762 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002763
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002764 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
2765 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
2766 continue;
2767 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002769 sinfo.ssrc = ssrc;
2770 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
2771 sinfo.bytes_sent = cs.bytesSent;
2772 sinfo.packets_sent = cs.packetsSent;
2773 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
2774 // returns 0 to indicate an error value.
2775 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
2776
2777 // Get data from the last remote RTCP report. Use default values if no data
2778 // available.
2779 sinfo.fraction_lost = -1.0;
2780 sinfo.jitter_ms = -1;
2781 sinfo.packets_lost = -1;
2782 sinfo.ext_seqnum = -1;
2783 std::vector<webrtc::ReportBlock> receive_blocks;
2784 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
2785 channel, &receive_blocks) != -1 &&
2786 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
2787 std::vector<webrtc::ReportBlock>::iterator iter;
2788 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
2789 ++iter) {
2790 // Lookup report for send ssrc only.
2791 if (iter->source_SSRC == sinfo.ssrc) {
2792 // Convert Q8 to floating point.
2793 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
2794 // Convert samples to milliseconds.
2795 if (codec.plfreq / 1000 > 0) {
2796 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
2797 }
2798 sinfo.packets_lost = iter->cumulative_num_packets_lost;
2799 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
2800 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002801 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 }
2803 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002804
2805 // Local speech level.
2806 sinfo.audio_level = (engine()->voe()->volume()->
2807 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
2808
2809 // TODO(xians): We are injecting the same APM logging to all the send
2810 // channels here because there is no good way to know which send channel
2811 // is using the APM. The correct fix is to allow the send channels to have
2812 // their own APM so that we can feed the correct APM logging to different
2813 // send channels. See issue crbug/264611 .
2814 sinfo.echo_return_loss = echo_return_loss;
2815 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
2816 sinfo.echo_delay_median_ms = echo_delay_median_ms;
2817 sinfo.echo_delay_std_ms = echo_delay_std_ms;
2818
2819 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820 }
2821
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 // Build the list of receivers, one for each receiving channel, or 1 in
2823 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002824 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002825 for (ChannelMap::const_iterator it = receive_channels_.begin();
2826 it != receive_channels_.end(); ++it) {
2827 channels.push_back(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002828 }
2829 if (channels.empty()) {
2830 channels.push_back(voe_channel());
2831 }
2832
2833 // Get the SSRC and stats for each receiver, based on our own calculations.
2834 for (std::vector<int>::const_iterator it = channels.begin();
2835 it != channels.end(); ++it) {
2836 memset(&cs, 0, sizeof(cs));
2837 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
2838 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
2839 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
2840 VoiceReceiverInfo rinfo;
2841 rinfo.ssrc = ssrc;
2842 rinfo.bytes_rcvd = cs.bytesReceived;
2843 rinfo.packets_rcvd = cs.packetsReceived;
2844 // The next four fields are from the most recently sent RTCP report.
2845 // Convert Q8 to floating point.
2846 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
2847 rinfo.packets_lost = cs.cumulativeLost;
2848 rinfo.ext_seqnum = cs.extendedMax;
2849 // Convert samples to milliseconds.
2850 if (codec.plfreq / 1000 > 0) {
2851 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
2852 }
2853
2854 // Get jitter buffer and total delay (alg + jitter + playout) stats.
2855 webrtc::NetworkStatistics ns;
2856 if (engine()->voe()->neteq() &&
2857 engine()->voe()->neteq()->GetNetworkStatistics(
2858 *it, ns) != -1) {
2859 rinfo.jitter_buffer_ms = ns.currentBufferSize;
2860 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
2861 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002862 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863 }
2864 if (engine()->voe()->sync()) {
2865 int playout_buffer_delay_ms = 0;
2866 engine()->voe()->sync()->GetDelayEstimate(
2867 *it, &rinfo.delay_estimate_ms, &playout_buffer_delay_ms);
2868 }
2869
2870 // Get speech level.
2871 rinfo.audio_level = (engine()->voe()->volume()->
2872 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
2873 info->receivers.push_back(rinfo);
2874 }
2875 }
2876
2877 return true;
2878}
2879
2880void WebRtcVoiceMediaChannel::GetLastMediaError(
2881 uint32* ssrc, VoiceMediaChannel::Error* error) {
2882 ASSERT(ssrc != NULL);
2883 ASSERT(error != NULL);
2884 FindSsrc(voe_channel(), ssrc);
2885 *error = WebRtcErrorToChannelError(GetLastEngineError());
2886}
2887
2888bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002889 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002891 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002892 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
2893 // This means the error is not limited to a specific channel. Signal the
2894 // message using ssrc=0. If the current channel is sending, use this
2895 // channel for sending the message.
2896 *ssrc = 0;
2897 return true;
2898 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002899 // Check whether this is a sending channel.
2900 for (ChannelMap::const_iterator it = send_channels_.begin();
2901 it != send_channels_.end(); ++it) {
2902 if (it->second.channel == channel_num) {
2903 // This is a sending channel.
2904 uint32 local_ssrc = 0;
2905 if (engine()->voe()->rtp()->GetLocalSSRC(
2906 channel_num, local_ssrc) != -1) {
2907 *ssrc = local_ssrc;
2908 }
2909 return true;
2910 }
2911 }
2912
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002914 for (ChannelMap::const_iterator it = receive_channels_.begin();
2915 it != receive_channels_.end(); ++it) {
2916 if (it->second.channel == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 *ssrc = it->first;
2918 return true;
2919 }
2920 }
2921 }
2922 return false;
2923}
2924
2925void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
2926 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
2927}
2928
2929int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
2930 unsigned int ulevel;
2931 int ret =
2932 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
2933 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2934}
2935
2936int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002937 ChannelMap::iterator it = receive_channels_.find(ssrc);
2938 if (it != receive_channels_.end())
2939 return it->second.channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
2941}
2942
2943int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002944 ChannelMap::iterator it = send_channels_.find(ssrc);
2945 if (it != send_channels_.end())
2946 return it->second.channel;
2947
2948 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002949}
2950
2951bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
2952 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
2953 // Get the RED encodings from the parameter with no name. This may
2954 // change based on what is discussed on the Jingle list.
2955 // The encoding parameter is of the form "a/b"; we only support where
2956 // a == b. Verify this and parse out the value into red_pt.
2957 // If the parameter value is absent (as it will be until we wire up the
2958 // signaling of this message), use the second codec specified (i.e. the
2959 // one after "red") as the encoding parameter.
2960 int red_pt = -1;
2961 std::string red_params;
2962 CodecParameterMap::const_iterator it = red_codec.params.find("");
2963 if (it != red_codec.params.end()) {
2964 red_params = it->second;
2965 std::vector<std::string> red_pts;
2966 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
2967 red_pts[0] != red_pts[1] ||
2968 !talk_base::FromString(red_pts[0], &red_pt)) {
2969 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
2970 return false;
2971 }
2972 } else if (red_codec.params.empty()) {
2973 LOG(LS_WARNING) << "RED params not present, using defaults";
2974 if (all_codecs.size() > 1) {
2975 red_pt = all_codecs[1].id;
2976 }
2977 }
2978
2979 // Try to find red_pt in |codecs|.
2980 std::vector<AudioCodec>::const_iterator codec;
2981 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
2982 if (codec->id == red_pt)
2983 break;
2984 }
2985
2986 // If we find the right codec, that will be the codec we pass to
2987 // SetSendCodec, with the desired payload type.
2988 if (codec != all_codecs.end() &&
2989 engine()->FindWebRtcCodec(*codec, send_codec)) {
2990 } else {
2991 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
2992 return false;
2993 }
2994
2995 return true;
2996}
2997
2998bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
2999 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003000 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001 return false;
3002 }
3003 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3004 // what we want to do with them.
3005 // engine()->voe().EnableVQMon(voe_channel(), true);
3006 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3007 return true;
3008}
3009
3010bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3011 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3012 for (int i = 0; i < ncodecs; ++i) {
3013 webrtc::CodecInst voe_codec;
3014 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3015 voe_codec.pltype = -1;
3016 if (engine()->voe()->codec()->SetRecPayloadType(
3017 channel, voe_codec) == -1) {
3018 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3019 return false;
3020 }
3021 }
3022 }
3023 return true;
3024}
3025
3026bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3027 if (playout) {
3028 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3029 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3030 LOG_RTCERR1(StartPlayout, channel);
3031 return false;
3032 }
3033 } else {
3034 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3035 engine()->voe()->base()->StopPlayout(channel);
3036 }
3037 return true;
3038}
3039
3040uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3041 bool rtcp) {
3042 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3043 uint32 ssrc = 0;
3044 if (len >= (ssrc_pos + sizeof(ssrc))) {
3045 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3046 }
3047 return ssrc;
3048}
3049
3050// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3051VoiceMediaChannel::Error
3052 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3053 switch (err_code) {
3054 case 0:
3055 return ERROR_NONE;
3056 case VE_CANNOT_START_RECORDING:
3057 case VE_MIC_VOL_ERROR:
3058 case VE_GET_MIC_VOL_ERROR:
3059 case VE_CANNOT_ACCESS_MIC_VOL:
3060 return ERROR_REC_DEVICE_OPEN_FAILED;
3061 case VE_SATURATION_WARNING:
3062 return ERROR_REC_DEVICE_SATURATION;
3063 case VE_REC_DEVICE_REMOVED:
3064 return ERROR_REC_DEVICE_REMOVED;
3065 case VE_RUNTIME_REC_WARNING:
3066 case VE_RUNTIME_REC_ERROR:
3067 return ERROR_REC_RUNTIME_ERROR;
3068 case VE_CANNOT_START_PLAYOUT:
3069 case VE_SPEAKER_VOL_ERROR:
3070 case VE_GET_SPEAKER_VOL_ERROR:
3071 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3072 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3073 case VE_RUNTIME_PLAY_WARNING:
3074 case VE_RUNTIME_PLAY_ERROR:
3075 return ERROR_PLAY_RUNTIME_ERROR;
3076 case VE_TYPING_NOISE_WARNING:
3077 return ERROR_REC_TYPING_NOISE_DETECTED;
3078 default:
3079 return VoiceMediaChannel::ERROR_OTHER;
3080 }
3081}
3082
3083int WebRtcSoundclipStream::Read(void *buf, int len) {
3084 size_t res = 0;
3085 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003086 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003087}
3088
3089int WebRtcSoundclipStream::Rewind() {
3090 mem_.Rewind();
3091 // Return -1 to keep VoiceEngine from looping.
3092 return (loop_) ? 0 : -1;
3093}
3094
3095} // namespace cricket
3096
3097#endif // HAVE_WEBRTC_VOICE