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