blob: 855a9e4236aa74393488123120274699a7c5becd [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(
1635 const std::vector<AudioCodec>& codecs) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001636 // TODO(xians): Break down this function into SetSendCodecs(channel, codecs)
1637 // to support per-channel codecs.
1638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639 // Disable DTMF, VAD, and FEC unless we know the other side wants them.
1640 dtmf_allowed_ = false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001641 for (ChannelMap::iterator iter = send_channels_.begin();
1642 iter != send_channels_.end(); ++iter) {
1643 engine()->voe()->codec()->SetVADStatus(iter->second.channel, false);
1644 engine()->voe()->rtp()->SetNACKStatus(iter->second.channel, false, 0);
1645 engine()->voe()->rtp()->SetFECStatus(iter->second.channel, false);
1646 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001647
1648 // Scan through the list to figure out the codec to use for sending, along
1649 // with the proper configuration for VAD and DTMF.
1650 bool first = true;
1651 webrtc::CodecInst send_codec;
1652 memset(&send_codec, 0, sizeof(send_codec));
1653
1654 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1655 it != codecs.end(); ++it) {
1656 // Ignore codecs we don't know about. The negotiation step should prevent
1657 // this, but double-check to be sure.
1658 webrtc::CodecInst voe_codec;
1659 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
1660 LOG(LS_WARNING) << "Unknown codec " << ToString(voe_codec);
1661 continue;
1662 }
1663
1664 // If OPUS, change what we send according to the "stereo" codec
1665 // parameter, and not the "channels" parameter. We set
1666 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1667 // the bitrate is not specified, i.e. is zero, we set it to the
1668 // appropriate default value for mono or stereo Opus.
1669 if (IsOpus(*it)) {
1670 if (IsOpusStereoEnabled(*it)) {
1671 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001672 if (!IsValidOpusBitrate(it->bitrate)) {
1673 if (it->bitrate != 0) {
1674 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1675 << it->bitrate
1676 << ") with default opus stereo bitrate: "
1677 << kOpusStereoBitrate;
1678 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679 voe_codec.rate = kOpusStereoBitrate;
1680 }
1681 } else {
1682 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001683 if (!IsValidOpusBitrate(it->bitrate)) {
1684 if (it->bitrate != 0) {
1685 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1686 << it->bitrate
1687 << ") with default opus mono bitrate: "
1688 << kOpusMonoBitrate;
1689 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 voe_codec.rate = kOpusMonoBitrate;
1691 }
1692 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001693 int bitrate_from_params = GetOpusBitrateFromParams(*it);
1694 if (bitrate_from_params != 0) {
1695 voe_codec.rate = bitrate_from_params;
1696 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001697 }
1698
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001699 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1700 // about it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1702 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001703 for (ChannelMap::iterator iter = send_channels_.begin();
1704 iter != send_channels_.end(); ++iter) {
1705 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
1706 iter->second.channel, it->id) == -1) {
1707 LOG_RTCERR2(SetSendTelephoneEventPayloadType,
1708 iter->second.channel, it->id);
1709 return false;
1710 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711 }
1712 dtmf_allowed_ = true;
1713 }
1714
1715 // Turn voice activity detection/comfort noise on if supported.
1716 // Set the wideband CN payload type appropriately.
1717 // (narrowband always uses the static payload type 13).
1718 if (_stricmp(it->name.c_str(), "CN") == 0) {
1719 webrtc::PayloadFrequencies cn_freq;
1720 switch (it->clockrate) {
1721 case 8000:
1722 cn_freq = webrtc::kFreq8000Hz;
1723 break;
1724 case 16000:
1725 cn_freq = webrtc::kFreq16000Hz;
1726 break;
1727 case 32000:
1728 cn_freq = webrtc::kFreq32000Hz;
1729 break;
1730 default:
1731 LOG(LS_WARNING) << "CN frequency " << it->clockrate
1732 << " not supported.";
1733 continue;
1734 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001735 // Loop through the existing send channels and set the CN payloadtype
1736 // and the VAD status.
1737 for (ChannelMap::iterator iter = send_channels_.begin();
1738 iter != send_channels_.end(); ++iter) {
1739 int channel = iter->second.channel;
1740 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1741 if (cn_freq != webrtc::kFreq8000Hz) {
1742 if (engine()->voe()->codec()->SetSendCNPayloadType(
1743 channel, it->id, cn_freq) == -1) {
1744 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
1745 // TODO(ajm): This failure condition will be removed from VoE.
1746 // Restore the return here when we update to a new enough webrtc.
1747 //
1748 // Not returning false because the SetSendCNPayloadType will fail if
1749 // the channel is already sending.
1750 // This can happen if the remote description is applied twice, for
1751 // example in the case of ROAP on top of JSEP, where both side will
1752 // send the offer.
1753 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001755
1756 // Only turn on VAD if we have a CN payload type that matches the
1757 // clockrate for the codec we are going to use.
1758 if (it->clockrate == send_codec.plfreq) {
1759 LOG(LS_INFO) << "Enabling VAD";
1760 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1761 LOG_RTCERR2(SetVADStatus, channel, true);
1762 return false;
1763 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 }
1765 }
1766 }
1767
1768 // We'll use the first codec in the list to actually send audio data.
1769 // Be sure to use the payload type requested by the remote side.
1770 // "red", for FEC audio, is a special case where the actual codec to be
1771 // used is specified in params.
1772 if (first) {
1773 if (_stricmp(it->name.c_str(), "red") == 0) {
1774 // Parse out the RED parameters. If we fail, just ignore RED;
1775 // we don't support all possible params/usage scenarios.
1776 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1777 continue;
1778 }
1779
1780 // Enable redundant encoding of the specified codec. Treat any
1781 // failure as a fatal internal error.
1782 LOG(LS_INFO) << "Enabling FEC";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001783 for (ChannelMap::iterator iter = send_channels_.begin();
1784 iter != send_channels_.end(); ++iter) {
1785 if (engine()->voe()->rtp()->SetFECStatus(iter->second.channel,
1786 true, it->id) == -1) {
1787 LOG_RTCERR3(SetFECStatus, iter->second.channel, true, it->id);
1788 return false;
1789 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790 }
1791 } else {
1792 send_codec = voe_codec;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001793 nack_enabled_ = IsNackEnabled(*it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001794 SetNack(send_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 }
1796 first = false;
1797 // Set the codec immediately, since SetVADStatus() depends on whether
1798 // the current codec is mono or stereo.
1799 if (!SetSendCodec(send_codec))
1800 return false;
1801 }
1802 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001803 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804
1805
1806 // If we're being asked to set an empty list of codecs, due to a buggy client,
1807 // choose the most common format: PCMU
1808 if (first) {
1809 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
1810 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
1811 engine()->FindWebRtcCodec(codec, &send_codec);
1812 if (!SetSendCodec(send_codec))
1813 return false;
1814 }
1815
1816 return true;
1817}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001818
1819void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
1820 bool nack_enabled) {
1821 for (ChannelMap::const_iterator it = channels.begin();
1822 it != channels.end(); ++it) {
1823 SetNack(it->first, it->second.channel, nack_enabled_);
1824 }
1825}
1826
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827void WebRtcVoiceMediaChannel::SetNack(uint32 ssrc, int channel,
1828 bool nack_enabled) {
1829 if (nack_enabled) {
1830 LOG(LS_INFO) << "Enabling NACK for stream " << ssrc;
1831 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1832 } else {
1833 LOG(LS_INFO) << "Disabling NACK for stream " << ssrc;
1834 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1835 }
1836}
1837
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838bool WebRtcVoiceMediaChannel::SetSendCodec(
1839 const webrtc::CodecInst& send_codec) {
1840 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
1841 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001842 for (ChannelMap::iterator iter = send_channels_.begin();
1843 iter != send_channels_.end(); ++iter) {
1844 if (!SetSendCodec(iter->second.channel, send_codec))
1845 return false;
1846 }
1847
1848 // All SetSendCodec calls were successful. Update the global state
1849 // accordingly.
1850 send_codec_.reset(new webrtc::CodecInst(send_codec));
1851
1852 return true;
1853}
1854
1855bool WebRtcVoiceMediaChannel::SetSendCodec(
1856 int channel, const webrtc::CodecInst& send_codec) {
1857 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1858 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1859
1860 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1861 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 return false;
1863 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 return true;
1865}
1866
1867bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
1868 const std::vector<RtpHeaderExtension>& extensions) {
1869 // We don't support any incoming extensions headers right now.
1870 return true;
1871}
1872
1873bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
1874 const std::vector<RtpHeaderExtension>& extensions) {
1875 // Enable the audio level extension header if requested.
1876 std::vector<RtpHeaderExtension>::const_iterator it;
1877 for (it = extensions.begin(); it != extensions.end(); ++it) {
1878 if (it->uri == kRtpAudioLevelHeaderExtension) {
1879 break;
1880 }
1881 }
1882
1883 bool enable = (it != extensions.end());
1884 int id = 0;
1885
1886 if (enable) {
1887 id = it->id;
1888 if (id < kMinRtpHeaderExtensionId ||
1889 id > kMaxRtpHeaderExtensionId) {
1890 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
1891 return false;
1892 }
1893 }
1894
1895 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001896 for (ChannelMap::const_iterator iter = send_channels_.begin();
1897 iter != send_channels_.end(); ++iter) {
1898 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
1899 iter->second.channel, enable, id) == -1) {
1900 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
1901 iter->second.channel, enable, id);
1902 return false;
1903 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 }
1905
1906 return true;
1907}
1908
1909bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1910 desired_playout_ = playout;
1911 return ChangePlayout(desired_playout_);
1912}
1913
1914bool WebRtcVoiceMediaChannel::PausePlayout() {
1915 return ChangePlayout(false);
1916}
1917
1918bool WebRtcVoiceMediaChannel::ResumePlayout() {
1919 return ChangePlayout(desired_playout_);
1920}
1921
1922bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
1923 if (playout_ == playout) {
1924 return true;
1925 }
1926
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001927 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001929 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 // Only toggle the default channel if we don't have any other channels.
1931 result = SetPlayout(voe_channel(), playout);
1932 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001933 for (ChannelMap::iterator it = receive_channels_.begin();
1934 it != receive_channels_.end() && result; ++it) {
1935 if (!SetPlayout(it->second.channel, playout)) {
1936 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
1937 << it->second.channel << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 result = false;
1939 }
1940 }
1941
1942 if (result) {
1943 playout_ = playout;
1944 }
1945 return result;
1946}
1947
1948bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
1949 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001950 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 return ChangeSend(desired_send_);
1952 return true;
1953}
1954
1955bool WebRtcVoiceMediaChannel::PauseSend() {
1956 return ChangeSend(SEND_NOTHING);
1957}
1958
1959bool WebRtcVoiceMediaChannel::ResumeSend() {
1960 return ChangeSend(desired_send_);
1961}
1962
1963bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
1964 if (send_ == send) {
1965 return true;
1966 }
1967
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001968 // Change the settings on each send channel.
1969 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 engine()->SetOptionOverrides(options_);
1971
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001972 // Change the settings on each send channel.
1973 for (ChannelMap::iterator iter = send_channels_.begin();
1974 iter != send_channels_.end(); ++iter) {
1975 if (!ChangeSend(iter->second.channel, send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001978
1979 // Clear up the options after stopping sending.
1980 if (send == SEND_NOTHING)
1981 engine()->ClearOptionOverrides();
1982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 send_ = send;
1984 return true;
1985}
1986
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001987bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
1988 if (send == SEND_MICROPHONE) {
1989 if (engine()->voe()->base()->StartSend(channel) == -1) {
1990 LOG_RTCERR1(StartSend, channel);
1991 return false;
1992 }
1993 if (engine()->voe()->file() &&
1994 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
1995 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
1996 return false;
1997 }
1998 } else { // SEND_NOTHING
1999 ASSERT(send == SEND_NOTHING);
2000 if (engine()->voe()->base()->StopSend(channel) == -1) {
2001 LOG_RTCERR1(StopSend, channel);
2002 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003 }
2004 }
2005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 return true;
2007}
2008
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002009void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2010 if (engine()->voe()->network()->RegisterExternalTransport(
2011 channel, *this) == -1) {
2012 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2013 }
2014
2015 // Enable RTCP (for quality stats and feedback messages)
2016 EnableRtcp(channel);
2017
2018 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2019 ResetRecvCodecs(channel);
2020}
2021
2022bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2023 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2024 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2025 }
2026
2027 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2028 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 return false;
2030 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002031
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002032 return true;
2033}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002034
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002035bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2036 // If the default channel is already used for sending create a new channel
2037 // otherwise use the default channel for sending.
2038 int channel = GetSendChannelNum(sp.first_ssrc());
2039 if (channel != -1) {
2040 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2041 return false;
2042 }
2043
2044 bool default_channel_is_available = true;
2045 for (ChannelMap::const_iterator iter = send_channels_.begin();
2046 iter != send_channels_.end(); ++iter) {
2047 if (IsDefaultChannel(iter->second.channel)) {
2048 default_channel_is_available = false;
2049 break;
2050 }
2051 }
2052 if (default_channel_is_available) {
2053 channel = voe_channel();
2054 } else {
2055 // Create a new channel for sending audio data.
2056 channel = engine()->voe()->base()->CreateChannel();
2057 if (channel == -1) {
2058 LOG_RTCERR0(CreateChannel);
2059 return false;
2060 }
2061
2062 ConfigureSendChannel(channel);
2063 }
2064
2065 // Save the channel to send_channels_, so that RemoveSendStream() can still
2066 // delete the channel in case failure happens below.
2067 send_channels_[sp.first_ssrc()] = WebRtcVoiceChannelInfo(channel, NULL);
2068
2069 // Set the send (local) SSRC.
2070 // If there are multiple send SSRCs, we can only set the first one here, and
2071 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2072 // (with a codec requires multiple SSRC(s)).
2073 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2074 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2075 return false;
2076 }
2077
2078 // At this point the channel's local SSRC has been updated. If the channel is
2079 // the default channel make sure that all the receive channels are updated as
2080 // well. Receive channels have to have the same SSRC as the default channel in
2081 // order to send receiver reports with this SSRC.
2082 if (IsDefaultChannel(channel)) {
2083 for (ChannelMap::const_iterator it = receive_channels_.begin();
2084 it != receive_channels_.end(); ++it) {
2085 // Only update the SSRC for non-default channels.
2086 if (!IsDefaultChannel(it->second.channel)) {
2087 if (engine()->voe()->rtp()->SetLocalSSRC(it->second.channel,
2088 sp.first_ssrc()) != 0) {
2089 LOG_RTCERR2(SetLocalSSRC, it->second.channel, sp.first_ssrc());
2090 return false;
2091 }
2092 }
2093 }
2094 }
2095
2096 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2097 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2098 return false;
2099 }
2100
2101 // Set the current codec to be used for the new channel.
2102 if (send_codec_ && !SetSendCodec(channel, *send_codec_))
2103 return false;
2104
2105 return ChangeSend(channel, desired_send_);
2106}
2107
2108bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2109 ChannelMap::iterator it = send_channels_.find(ssrc);
2110 if (it == send_channels_.end()) {
2111 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2112 << " which doesn't exist.";
2113 return false;
2114 }
2115
2116 int channel = it->second.channel;
2117 ChangeSend(channel, SEND_NOTHING);
2118
2119 // Notify the audio renderer that the send channel is going away.
2120 if (it->second.renderer)
2121 it->second.renderer->RemoveChannel(channel);
2122
2123 if (IsDefaultChannel(channel)) {
2124 // Do not delete the default channel since the receive channels depend on
2125 // the default channel, recycle it instead.
2126 ChangeSend(channel, SEND_NOTHING);
2127 } else {
2128 // Clean up and delete the send channel.
2129 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2130 << " with VoiceEngine channel #" << channel << ".";
2131 if (!DeleteChannel(channel))
2132 return false;
2133 }
2134
2135 send_channels_.erase(it);
2136 if (send_channels_.empty())
2137 ChangeSend(SEND_NOTHING);
2138
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 return true;
2140}
2141
2142bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002143 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144
2145 if (!VERIFY(sp.ssrcs.size() == 1))
2146 return false;
2147 uint32 ssrc = sp.first_ssrc();
2148
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002149 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2150 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 return false;
2152 }
2153
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002154 // Reuse default channel for recv stream in non-conference mode call
2155 // when the default channel is not being used.
2156 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2157 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2158 << " reuse default channel";
2159 default_receive_ssrc_ = sp.first_ssrc();
2160 receive_channels_.insert(std::make_pair(
2161 default_receive_ssrc_, WebRtcVoiceChannelInfo(voe_channel(), NULL)));
2162 return SetPlayout(voe_channel(), playout_);
2163 }
2164
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 // Create a new channel for receiving audio data.
2166 int channel = engine()->voe()->base()->CreateChannel();
2167 if (channel == -1) {
2168 LOG_RTCERR0(CreateChannel);
2169 return false;
2170 }
2171
2172 // Configure to use external transport, like our default channel.
2173 if (engine()->voe()->network()->RegisterExternalTransport(
2174 channel, *this) == -1) {
2175 LOG_RTCERR2(SetExternalTransport, channel, this);
2176 return false;
2177 }
2178
2179 // Use the same SSRC as our default channel (so the RTCP reports are correct).
2180 unsigned int send_ssrc;
2181 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2182 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
2183 LOG_RTCERR2(GetSendSSRC, channel, send_ssrc);
2184 return false;
2185 }
2186 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
2187 LOG_RTCERR2(SetSendSSRC, channel, send_ssrc);
2188 return false;
2189 }
2190
2191 // Use the same recv payload types as our default channel.
2192 ResetRecvCodecs(channel);
2193 if (!recv_codecs_.empty()) {
2194 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2195 it != recv_codecs_.end(); ++it) {
2196 webrtc::CodecInst voe_codec;
2197 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2198 voe_codec.pltype = it->id;
2199 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2200 if (engine()->voe()->codec()->GetRecPayloadType(
2201 voe_channel(), voe_codec) != -1) {
2202 if (engine()->voe()->codec()->SetRecPayloadType(
2203 channel, voe_codec) == -1) {
2204 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2205 return false;
2206 }
2207 }
2208 }
2209 }
2210 }
2211
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002212 if (InConferenceMode()) {
2213 // To be in par with the video, voe_channel() is not used for receiving in
2214 // a conference call.
2215 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2216 // This is the first stream in a multi user meeting. We can now
2217 // disable playback of the default stream. This since the default
2218 // stream will probably have received some initial packets before
2219 // the new stream was added. This will mean that the CN state from
2220 // the default channel will be mixed in with the other streams
2221 // throughout the whole meeting, which might be disturbing.
2222 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2223 SetPlayout(voe_channel(), false);
2224 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 }
2226 SetNack(ssrc, channel, nack_enabled_);
2227
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002228 receive_channels_.insert(
2229 std::make_pair(ssrc, WebRtcVoiceChannelInfo(channel, NULL)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230
2231 // TODO(juberti): We should rollback the add if SetPlayout fails.
2232 LOG(LS_INFO) << "New audio stream " << ssrc
2233 << " registered to VoiceEngine channel #"
2234 << channel << ".";
2235 return SetPlayout(channel, playout_);
2236}
2237
2238bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002239 talk_base::CritScope lock(&receive_channels_cs_);
2240 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002241 if (it == receive_channels_.end()) {
2242 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2243 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002244 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002245 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002247 if (ssrc == default_receive_ssrc_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002248 ASSERT(IsDefaultChannel(it->second.channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002249 // Recycle the default channel is for recv stream.
2250 if (playout_)
2251 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002253 if (it->second.renderer)
2254 it->second.renderer->RemoveChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002256 default_receive_ssrc_ = 0;
2257 receive_channels_.erase(it);
2258 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002260
2261 // Non default channel.
2262 // Notify the renderer that channel is going away.
2263 if (it->second.renderer)
2264 it->second.renderer->RemoveChannel(it->second.channel);
2265
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002266 LOG(LS_INFO) << "Removing audio stream " << ssrc
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002267 << " with VoiceEngine channel #" << it->second.channel << ".";
2268 if (!DeleteChannel(it->second.channel)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002269 // Erase the entry anyhow.
2270 receive_channels_.erase(it);
2271 return false;
2272 }
2273
2274 receive_channels_.erase(it);
2275 bool enable_default_channel_playout = false;
2276 if (receive_channels_.empty()) {
2277 // The last stream was removed. We can now enable the default
2278 // channel for new channels to be played out immediately without
2279 // waiting for AddStream messages.
2280 // We do this for both conference mode and non-conference mode.
2281 // TODO(oja): Does the default channel still have it's CN state?
2282 enable_default_channel_playout = true;
2283 }
2284 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2285 default_receive_ssrc_ != 0) {
2286 // Only the default channel is active, enable the playout on default
2287 // channel.
2288 enable_default_channel_playout = true;
2289 }
2290 if (enable_default_channel_playout && playout_) {
2291 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2292 SetPlayout(voe_channel(), true);
2293 }
2294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 return true;
2296}
2297
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002298bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2299 AudioRenderer* renderer) {
2300 ChannelMap::iterator it = receive_channels_.find(ssrc);
2301 if (it == receive_channels_.end()) {
2302 if (renderer) {
2303 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002304 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002305 return false;
2306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002308 // The channel likely has gone away, do nothing.
2309 return true;
2310 }
2311
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002312 AudioRenderer* remote_renderer = it->second.renderer;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002313 if (renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002314 ASSERT(remote_renderer == NULL || remote_renderer == renderer);
2315 if (!remote_renderer) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002316 renderer->AddChannel(it->second.channel);
2317 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002318 } else if (remote_renderer) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002319 // |renderer| == NULL, remove the channel from the renderer.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002320 remote_renderer->RemoveChannel(it->second.channel);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002321 }
2322
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002323 // Assign the new value to the struct.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002324 it->second.renderer = renderer;
2325 return true;
2326}
2327
2328bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2329 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002330 ChannelMap::iterator it = send_channels_.find(ssrc);
2331 if (it == send_channels_.end()) {
2332 if (renderer) {
2333 // Return an error if trying to set a valid renderer with an invalid ssrc.
2334 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2335 return false;
2336 }
2337
2338 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002339 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002340 }
2341
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002342 AudioRenderer* local_renderer = it->second.renderer;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002343 if (renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 ASSERT(local_renderer == NULL || local_renderer == renderer);
2345 if (!local_renderer)
2346 renderer->AddChannel(it->second.channel);
2347 } else if (local_renderer) {
2348 local_renderer->RemoveChannel(it->second.channel);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002349 }
2350
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002351 // Assign the new value to the struct.
2352 it->second.renderer = renderer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::GetActiveStreams(
2357 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002358 // In conference mode, the default channel should not be in
2359 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002361 for (ChannelMap::iterator it = receive_channels_.begin();
2362 it != receive_channels_.end(); ++it) {
2363 int level = GetOutputLevel(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 if (level > 0) {
2365 actives->push_back(std::make_pair(it->first, level));
2366 }
2367 }
2368 return true;
2369}
2370
2371int WebRtcVoiceMediaChannel::GetOutputLevel() {
2372 // return the highest output level of all streams
2373 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002374 for (ChannelMap::iterator it = receive_channels_.begin();
2375 it != receive_channels_.end(); ++it) {
2376 int level = GetOutputLevel(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 highest = talk_base::_max(level, highest);
2378 }
2379 return highest;
2380}
2381
2382int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2383 int ret;
2384 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2385 // In case of error, log the info and continue
2386 LOG_RTCERR0(TimeSinceLastTyping);
2387 ret = -1;
2388 } else {
2389 ret *= 1000; // We return ms, webrtc returns seconds.
2390 }
2391 return ret;
2392}
2393
2394void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2395 int cost_per_typing, int reporting_threshold, int penalty_decay,
2396 int type_event_delay) {
2397 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2398 time_window, cost_per_typing,
2399 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2400 // In case of error, log the info and continue
2401 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2402 cost_per_typing, reporting_threshold, penalty_decay,
2403 type_event_delay);
2404 }
2405}
2406
2407bool WebRtcVoiceMediaChannel::SetOutputScaling(
2408 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002409 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 // Collect the channels to scale the output volume.
2411 std::vector<int> channels;
2412 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002413 // Default channel is not in receive_channels_ if it is not being used for
2414 // playout.
2415 if (default_receive_ssrc_ == 0)
2416 channels.push_back(voe_channel());
2417 for (ChannelMap::const_iterator it = receive_channels_.begin();
2418 it != receive_channels_.end(); ++it) {
2419 channels.push_back(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002420 }
2421 } else { // Collect only the channel of the specified ssrc.
2422 int channel = GetReceiveChannelNum(ssrc);
2423 if (-1 == channel) {
2424 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2425 return false;
2426 }
2427 channels.push_back(channel);
2428 }
2429
2430 // Scale the output volume for the collected channels. We first normalize to
2431 // scale the volume and then set the left and right pan.
2432 float scale = static_cast<float>(talk_base::_max(left, right));
2433 if (scale > 0.0001f) {
2434 left /= scale;
2435 right /= scale;
2436 }
2437 for (std::vector<int>::const_iterator it = channels.begin();
2438 it != channels.end(); ++it) {
2439 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2440 *it, scale)) {
2441 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2442 return false;
2443 }
2444 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2445 *it, static_cast<float>(left), static_cast<float>(right))) {
2446 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2447 // Do not return if fails. SetOutputVolumePan is not available for all
2448 // pltforms.
2449 }
2450 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2451 << " right=" << right * scale
2452 << " for channel " << *it << " and ssrc " << ssrc;
2453 }
2454 return true;
2455}
2456
2457bool WebRtcVoiceMediaChannel::GetOutputScaling(
2458 uint32 ssrc, double* left, double* right) {
2459 if (!left || !right) return false;
2460
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002461 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002462 // Determine which channel based on ssrc.
2463 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2464 if (channel == -1) {
2465 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2466 return false;
2467 }
2468
2469 float scaling;
2470 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2471 channel, scaling)) {
2472 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2473 return false;
2474 }
2475
2476 float left_pan;
2477 float right_pan;
2478 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2479 channel, left_pan, right_pan)) {
2480 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2481 // If GetOutputVolumePan fails, we use the default left and right pan.
2482 left_pan = 1.0f;
2483 right_pan = 1.0f;
2484 }
2485
2486 *left = scaling * left_pan;
2487 *right = scaling * right_pan;
2488 return true;
2489}
2490
2491bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2492 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2493 return true;
2494}
2495
2496bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2497 bool play, bool loop) {
2498 if (!ringback_tone_) {
2499 return false;
2500 }
2501
2502 // The voe file api is not available in chrome.
2503 if (!engine()->voe()->file()) {
2504 return false;
2505 }
2506
2507 // Determine which VoiceEngine channel to play on.
2508 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2509 if (channel == -1) {
2510 return false;
2511 }
2512
2513 // Make sure the ringtone is cued properly, and play it out.
2514 if (play) {
2515 ringback_tone_->set_loop(loop);
2516 ringback_tone_->Rewind();
2517 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2518 ringback_tone_.get()) == -1) {
2519 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2520 LOG(LS_ERROR) << "Unable to start ringback tone";
2521 return false;
2522 }
2523 ringback_channels_.insert(channel);
2524 LOG(LS_INFO) << "Started ringback on channel " << channel;
2525 } else {
2526 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2527 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2528 LOG_RTCERR1(StopPlayingFileLocally, channel);
2529 return false;
2530 }
2531 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2532 ringback_channels_.erase(channel);
2533 }
2534
2535 return true;
2536}
2537
2538bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2539 return dtmf_allowed_;
2540}
2541
2542bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2543 int duration, int flags) {
2544 if (!dtmf_allowed_) {
2545 return false;
2546 }
2547
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 // Send the event.
2549 if (flags & cricket::DF_SEND) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002550 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2551 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002552 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2553 << ssrc << " is not in use.";
2554 return false;
2555 }
2556 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002557 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2558 channel, event, true, duration) == -1) {
2559 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560 return false;
2561 }
2562 }
2563
2564 // Play the event.
2565 if (flags & cricket::DF_PLAY) {
2566 // Play DTMF tone locally.
2567 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2568 LOG_RTCERR2(PlayDtmfTone, event, duration);
2569 return false;
2570 }
2571 }
2572
2573 return true;
2574}
2575
2576void WebRtcVoiceMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
2577 // Pick which channel to send this packet to. If this packet doesn't match
2578 // any multiplexed streams, just send it to the default channel. Otherwise,
2579 // send it to the specific decoder instance for that stream.
2580 int which_channel = GetReceiveChannelNum(
2581 ParseSsrc(packet->data(), packet->length(), false));
2582 if (which_channel == -1) {
2583 which_channel = voe_channel();
2584 }
2585
2586 // Stop any ringback that might be playing on the channel.
2587 // It's possible the ringback has already stopped, ih which case we'll just
2588 // use the opportunity to remove the channel from ringback_channels_.
2589 if (engine()->voe()->file()) {
2590 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2591 if (it != ringback_channels_.end()) {
2592 if (engine()->voe()->file()->IsPlayingFileLocally(
2593 which_channel) == 1) {
2594 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2595 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2596 << " due to incoming media";
2597 }
2598 ringback_channels_.erase(which_channel);
2599 }
2600 }
2601
2602 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002603 engine()->voe()->network()->ReceivedRTPPacket(
2604 which_channel,
2605 packet->data(),
2606 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002607}
2608
2609void WebRtcVoiceMediaChannel::OnRtcpReceived(talk_base::Buffer* packet) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002610 // Sending channels need all RTCP packets with feedback information.
2611 // Even sender reports can contain attached report blocks.
2612 // Receiving channels need sender reports in order to create
2613 // correct receiver reports.
2614 int type = 0;
2615 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2616 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2617 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618 }
2619
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002620 // If it is a sender report, find the channel that is listening.
2621 bool has_sent_to_default_channel = false;
2622 if (type == kRtcpTypeSR) {
2623 int which_channel = GetReceiveChannelNum(
2624 ParseSsrc(packet->data(), packet->length(), true));
2625 if (which_channel != -1) {
2626 engine()->voe()->network()->ReceivedRTCPPacket(
2627 which_channel,
2628 packet->data(),
2629 static_cast<unsigned int>(packet->length()));
2630
2631 if (IsDefaultChannel(which_channel))
2632 has_sent_to_default_channel = true;
2633 }
2634 }
2635
2636 // SR may continue RR and any RR entry may correspond to any one of the send
2637 // channels. So all RTCP packets must be forwarded all send channels. VoE
2638 // will filter out RR internally.
2639 for (ChannelMap::iterator iter = send_channels_.begin();
2640 iter != send_channels_.end(); ++iter) {
2641 // Make sure not sending the same packet to default channel more than once.
2642 if (IsDefaultChannel(iter->second.channel) && has_sent_to_default_channel)
2643 continue;
2644
2645 engine()->voe()->network()->ReceivedRTCPPacket(
2646 iter->second.channel,
2647 packet->data(),
2648 static_cast<unsigned int>(packet->length()));
2649 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002650}
2651
2652bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002653 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2654 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2656 return false;
2657 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002658 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2659 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002660 return false;
2661 }
2662 return true;
2663}
2664
2665bool WebRtcVoiceMediaChannel::SetSendBandwidth(bool autobw, int bps) {
2666 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
2667
2668 if (!send_codec_) {
2669 LOG(LS_INFO) << "The send codec has not been set up yet.";
2670 return false;
2671 }
2672
2673 // Bandwidth is auto by default.
2674 if (autobw || bps <= 0)
2675 return true;
2676
2677 webrtc::CodecInst codec = *send_codec_;
2678 bool is_multi_rate = IsCodecMultiRate(codec);
2679
2680 if (is_multi_rate) {
2681 // If codec is multi-rate then just set the bitrate.
2682 codec.rate = bps;
2683 if (!SetSendCodec(codec)) {
2684 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2685 << " to bitrate " << bps << " bps.";
2686 return false;
2687 }
2688 return true;
2689 } else {
2690 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2691 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2692 // fixed bitrate then ignore.
2693 if (bps < codec.rate) {
2694 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2695 << " to bitrate " << bps << " bps"
2696 << ", requires at least " << codec.rate << " bps.";
2697 return false;
2698 }
2699 return true;
2700 }
2701}
2702
2703bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002704 bool echo_metrics_on = false;
2705 // These can take on valid negative values, so use the lowest possible level
2706 // as default rather than -1.
2707 int echo_return_loss = -100;
2708 int echo_return_loss_enhancement = -100;
2709 // These can also be negative, but in practice -1 is only used to signal
2710 // insufficient data, since the resolution is limited to multiples of 4 ms.
2711 int echo_delay_median_ms = -1;
2712 int echo_delay_std_ms = -1;
2713 if (engine()->voe()->processing()->GetEcMetricsStatus(
2714 echo_metrics_on) != -1 && echo_metrics_on) {
2715 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
2716 // here, but it appears to be unsuitable currently. Revisit after this is
2717 // investigated: http://b/issue?id=5666755
2718 int erl, erle, rerl, anlp;
2719 if (engine()->voe()->processing()->GetEchoMetrics(
2720 erl, erle, rerl, anlp) != -1) {
2721 echo_return_loss = erl;
2722 echo_return_loss_enhancement = erle;
2723 }
2724
2725 int median, std;
2726 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
2727 echo_delay_median_ms = median;
2728 echo_delay_std_ms = std;
2729 }
2730 }
2731
2732
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002733 webrtc::CallStatistics cs;
2734 unsigned int ssrc;
2735 webrtc::CodecInst codec;
2736 unsigned int level;
2737
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002738 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
2739 channel_iter != send_channels_.end(); ++channel_iter) {
2740 const int channel = channel_iter->second.channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002742 // Fill in the sender info, based on what we know, and what the
2743 // remote side told us it got from its RTCP report.
2744 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002746 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
2747 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
2748 continue;
2749 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002750
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002751 sinfo.ssrc = ssrc;
2752 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
2753 sinfo.bytes_sent = cs.bytesSent;
2754 sinfo.packets_sent = cs.packetsSent;
2755 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
2756 // returns 0 to indicate an error value.
2757 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
2758
2759 // Get data from the last remote RTCP report. Use default values if no data
2760 // available.
2761 sinfo.fraction_lost = -1.0;
2762 sinfo.jitter_ms = -1;
2763 sinfo.packets_lost = -1;
2764 sinfo.ext_seqnum = -1;
2765 std::vector<webrtc::ReportBlock> receive_blocks;
2766 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
2767 channel, &receive_blocks) != -1 &&
2768 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
2769 std::vector<webrtc::ReportBlock>::iterator iter;
2770 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
2771 ++iter) {
2772 // Lookup report for send ssrc only.
2773 if (iter->source_SSRC == sinfo.ssrc) {
2774 // Convert Q8 to floating point.
2775 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
2776 // Convert samples to milliseconds.
2777 if (codec.plfreq / 1000 > 0) {
2778 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
2779 }
2780 sinfo.packets_lost = iter->cumulative_num_packets_lost;
2781 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
2782 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002783 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784 }
2785 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002786
2787 // Local speech level.
2788 sinfo.audio_level = (engine()->voe()->volume()->
2789 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
2790
2791 // TODO(xians): We are injecting the same APM logging to all the send
2792 // channels here because there is no good way to know which send channel
2793 // is using the APM. The correct fix is to allow the send channels to have
2794 // their own APM so that we can feed the correct APM logging to different
2795 // send channels. See issue crbug/264611 .
2796 sinfo.echo_return_loss = echo_return_loss;
2797 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
2798 sinfo.echo_delay_median_ms = echo_delay_median_ms;
2799 sinfo.echo_delay_std_ms = echo_delay_std_ms;
2800
2801 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 }
2803
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002804 // Build the list of receivers, one for each receiving channel, or 1 in
2805 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002807 for (ChannelMap::const_iterator it = receive_channels_.begin();
2808 it != receive_channels_.end(); ++it) {
2809 channels.push_back(it->second.channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002810 }
2811 if (channels.empty()) {
2812 channels.push_back(voe_channel());
2813 }
2814
2815 // Get the SSRC and stats for each receiver, based on our own calculations.
2816 for (std::vector<int>::const_iterator it = channels.begin();
2817 it != channels.end(); ++it) {
2818 memset(&cs, 0, sizeof(cs));
2819 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
2820 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
2821 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
2822 VoiceReceiverInfo rinfo;
2823 rinfo.ssrc = ssrc;
2824 rinfo.bytes_rcvd = cs.bytesReceived;
2825 rinfo.packets_rcvd = cs.packetsReceived;
2826 // The next four fields are from the most recently sent RTCP report.
2827 // Convert Q8 to floating point.
2828 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
2829 rinfo.packets_lost = cs.cumulativeLost;
2830 rinfo.ext_seqnum = cs.extendedMax;
2831 // Convert samples to milliseconds.
2832 if (codec.plfreq / 1000 > 0) {
2833 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
2834 }
2835
2836 // Get jitter buffer and total delay (alg + jitter + playout) stats.
2837 webrtc::NetworkStatistics ns;
2838 if (engine()->voe()->neteq() &&
2839 engine()->voe()->neteq()->GetNetworkStatistics(
2840 *it, ns) != -1) {
2841 rinfo.jitter_buffer_ms = ns.currentBufferSize;
2842 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
2843 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002844 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 }
2846 if (engine()->voe()->sync()) {
2847 int playout_buffer_delay_ms = 0;
2848 engine()->voe()->sync()->GetDelayEstimate(
2849 *it, &rinfo.delay_estimate_ms, &playout_buffer_delay_ms);
2850 }
2851
2852 // Get speech level.
2853 rinfo.audio_level = (engine()->voe()->volume()->
2854 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
2855 info->receivers.push_back(rinfo);
2856 }
2857 }
2858
2859 return true;
2860}
2861
2862void WebRtcVoiceMediaChannel::GetLastMediaError(
2863 uint32* ssrc, VoiceMediaChannel::Error* error) {
2864 ASSERT(ssrc != NULL);
2865 ASSERT(error != NULL);
2866 FindSsrc(voe_channel(), ssrc);
2867 *error = WebRtcErrorToChannelError(GetLastEngineError());
2868}
2869
2870bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002871 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002872 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002873 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002874 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
2875 // This means the error is not limited to a specific channel. Signal the
2876 // message using ssrc=0. If the current channel is sending, use this
2877 // channel for sending the message.
2878 *ssrc = 0;
2879 return true;
2880 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002881 // Check whether this is a sending channel.
2882 for (ChannelMap::const_iterator it = send_channels_.begin();
2883 it != send_channels_.end(); ++it) {
2884 if (it->second.channel == channel_num) {
2885 // This is a sending channel.
2886 uint32 local_ssrc = 0;
2887 if (engine()->voe()->rtp()->GetLocalSSRC(
2888 channel_num, local_ssrc) != -1) {
2889 *ssrc = local_ssrc;
2890 }
2891 return true;
2892 }
2893 }
2894
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896 for (ChannelMap::const_iterator it = receive_channels_.begin();
2897 it != receive_channels_.end(); ++it) {
2898 if (it->second.channel == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899 *ssrc = it->first;
2900 return true;
2901 }
2902 }
2903 }
2904 return false;
2905}
2906
2907void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
2908 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
2909}
2910
2911int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
2912 unsigned int ulevel;
2913 int ret =
2914 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
2915 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2916}
2917
2918int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002919 ChannelMap::iterator it = receive_channels_.find(ssrc);
2920 if (it != receive_channels_.end())
2921 return it->second.channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
2923}
2924
2925int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002926 ChannelMap::iterator it = send_channels_.find(ssrc);
2927 if (it != send_channels_.end())
2928 return it->second.channel;
2929
2930 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931}
2932
2933bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
2934 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
2935 // Get the RED encodings from the parameter with no name. This may
2936 // change based on what is discussed on the Jingle list.
2937 // The encoding parameter is of the form "a/b"; we only support where
2938 // a == b. Verify this and parse out the value into red_pt.
2939 // If the parameter value is absent (as it will be until we wire up the
2940 // signaling of this message), use the second codec specified (i.e. the
2941 // one after "red") as the encoding parameter.
2942 int red_pt = -1;
2943 std::string red_params;
2944 CodecParameterMap::const_iterator it = red_codec.params.find("");
2945 if (it != red_codec.params.end()) {
2946 red_params = it->second;
2947 std::vector<std::string> red_pts;
2948 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
2949 red_pts[0] != red_pts[1] ||
2950 !talk_base::FromString(red_pts[0], &red_pt)) {
2951 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
2952 return false;
2953 }
2954 } else if (red_codec.params.empty()) {
2955 LOG(LS_WARNING) << "RED params not present, using defaults";
2956 if (all_codecs.size() > 1) {
2957 red_pt = all_codecs[1].id;
2958 }
2959 }
2960
2961 // Try to find red_pt in |codecs|.
2962 std::vector<AudioCodec>::const_iterator codec;
2963 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
2964 if (codec->id == red_pt)
2965 break;
2966 }
2967
2968 // If we find the right codec, that will be the codec we pass to
2969 // SetSendCodec, with the desired payload type.
2970 if (codec != all_codecs.end() &&
2971 engine()->FindWebRtcCodec(*codec, send_codec)) {
2972 } else {
2973 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
2974 return false;
2975 }
2976
2977 return true;
2978}
2979
2980bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
2981 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002982 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002983 return false;
2984 }
2985 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
2986 // what we want to do with them.
2987 // engine()->voe().EnableVQMon(voe_channel(), true);
2988 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
2989 return true;
2990}
2991
2992bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
2993 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
2994 for (int i = 0; i < ncodecs; ++i) {
2995 webrtc::CodecInst voe_codec;
2996 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
2997 voe_codec.pltype = -1;
2998 if (engine()->voe()->codec()->SetRecPayloadType(
2999 channel, voe_codec) == -1) {
3000 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3001 return false;
3002 }
3003 }
3004 }
3005 return true;
3006}
3007
3008bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3009 if (playout) {
3010 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3011 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3012 LOG_RTCERR1(StartPlayout, channel);
3013 return false;
3014 }
3015 } else {
3016 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3017 engine()->voe()->base()->StopPlayout(channel);
3018 }
3019 return true;
3020}
3021
3022uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3023 bool rtcp) {
3024 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3025 uint32 ssrc = 0;
3026 if (len >= (ssrc_pos + sizeof(ssrc))) {
3027 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3028 }
3029 return ssrc;
3030}
3031
3032// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3033VoiceMediaChannel::Error
3034 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3035 switch (err_code) {
3036 case 0:
3037 return ERROR_NONE;
3038 case VE_CANNOT_START_RECORDING:
3039 case VE_MIC_VOL_ERROR:
3040 case VE_GET_MIC_VOL_ERROR:
3041 case VE_CANNOT_ACCESS_MIC_VOL:
3042 return ERROR_REC_DEVICE_OPEN_FAILED;
3043 case VE_SATURATION_WARNING:
3044 return ERROR_REC_DEVICE_SATURATION;
3045 case VE_REC_DEVICE_REMOVED:
3046 return ERROR_REC_DEVICE_REMOVED;
3047 case VE_RUNTIME_REC_WARNING:
3048 case VE_RUNTIME_REC_ERROR:
3049 return ERROR_REC_RUNTIME_ERROR;
3050 case VE_CANNOT_START_PLAYOUT:
3051 case VE_SPEAKER_VOL_ERROR:
3052 case VE_GET_SPEAKER_VOL_ERROR:
3053 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3054 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3055 case VE_RUNTIME_PLAY_WARNING:
3056 case VE_RUNTIME_PLAY_ERROR:
3057 return ERROR_PLAY_RUNTIME_ERROR;
3058 case VE_TYPING_NOISE_WARNING:
3059 return ERROR_REC_TYPING_NOISE_DETECTED;
3060 default:
3061 return VoiceMediaChannel::ERROR_OTHER;
3062 }
3063}
3064
3065int WebRtcSoundclipStream::Read(void *buf, int len) {
3066 size_t res = 0;
3067 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003068 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003069}
3070
3071int WebRtcSoundclipStream::Rewind() {
3072 mem_.Rewind();
3073 // Return -1 to keep VoiceEngine from looping.
3074 return (loop_) ? 0 : -1;
3075}
3076
3077} // namespace cricket
3078
3079#endif // HAVE_WEBRTC_VOICE