blob: e2415cf569d86aabf1b36b8fb36a5b86efb00448 [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;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000128// Default audio dscp value.
129// See http://tools.ietf.org/html/rfc2474 for details.
130// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
131static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000133// Ensure we open the file in a writeable path on ChromeOS and Android. This
134// workaround can be removed when it's possible to specify a filename for audio
135// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000136//
137// TODO(grunell): Use a string in the options instead of hardcoding it here
138// and let the embedder choose the filename (crbug.com/264223).
139//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
141// below.
142#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144#elif defined(ANDROID)
145static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000146#else
147static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
148#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Dumps an AudioCodec in RFC 2327-ish format.
151static std::string ToString(const AudioCodec& codec) {
152 std::stringstream ss;
153 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154 << " (" << codec.id << ")";
155 return ss.str();
156}
157static std::string ToString(const webrtc::CodecInst& codec) {
158 std::stringstream ss;
159 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160 << " (" << codec.pltype << ")";
161 return ss.str();
162}
163
164static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
165 const char* delim = "\r\n";
166 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
167 LOG_V(sev) << tok;
168 }
169}
170
171// Severity is an integer because it comes is assumed to be from command line.
172static int SeverityToFilter(int severity) {
173 int filter = webrtc::kTraceNone;
174 switch (severity) {
175 case talk_base::LS_VERBOSE:
176 filter |= webrtc::kTraceAll;
177 case talk_base::LS_INFO:
178 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
179 case talk_base::LS_WARNING:
180 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
181 case talk_base::LS_ERROR:
182 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
183 }
184 return filter;
185}
186
187static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190 kCodecPrefs[i].clockrate == codec.plfreq) {
191 return kCodecPrefs[i].is_multi_rate;
192 }
193 }
194 return false;
195}
196
197static bool FindCodec(const std::vector<AudioCodec>& codecs,
198 const AudioCodec& codec,
199 AudioCodec* found_codec) {
200 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
201 it != codecs.end(); ++it) {
202 if (it->Matches(codec)) {
203 if (found_codec != NULL) {
204 *found_codec = *it;
205 }
206 return true;
207 }
208 }
209 return false;
210}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000211
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212static bool IsNackEnabled(const AudioCodec& codec) {
213 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
214 kParamValueEmpty));
215}
216
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217// Gets the default set of options applied to the engine. Historically, these
218// were supplied as a combination of flags from the channel manager (ec, agc,
219// ns, and highpass) and the rest hardcoded in InitInternal.
220static AudioOptions GetDefaultEngineOptions() {
221 AudioOptions options;
222 options.echo_cancellation.Set(true);
223 options.auto_gain_control.Set(true);
224 options.noise_suppression.Set(true);
225 options.highpass_filter.Set(true);
226 options.stereo_swapping.Set(false);
227 options.typing_detection.Set(true);
228 options.conference_mode.Set(false);
229 options.adjust_agc_delta.Set(0);
230 options.experimental_agc.Set(false);
231 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000232 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000233 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000234 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000235 return options;
236}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000237
238class WebRtcSoundclipMedia : public SoundclipMedia {
239 public:
240 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
241 : engine_(engine), webrtc_channel_(-1) {
242 engine_->RegisterSoundclip(this);
243 }
244
245 virtual ~WebRtcSoundclipMedia() {
246 engine_->UnregisterSoundclip(this);
247 if (webrtc_channel_ != -1) {
248 // We shouldn't have to call Disable() here. DeleteChannel() should call
249 // StopPlayout() while deleting the channel. We should fix the bug
250 // inside WebRTC and remove the Disable() call bellow. This work is
251 // tracked by bug http://b/issue?id=5382855.
252 PlaySound(NULL, 0, 0);
253 Disable();
254 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
255 == -1) {
256 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
257 }
258 }
259 }
260
261 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000262 if (!engine_->voe_sc()) {
263 return false;
264 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000265 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266 if (webrtc_channel_ == -1) {
267 LOG_RTCERR0(CreateChannel);
268 return false;
269 }
270 return true;
271 }
272
273 bool Enable() {
274 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
275 LOG_RTCERR1(StartPlayout, webrtc_channel_);
276 return false;
277 }
278 return true;
279 }
280
281 bool Disable() {
282 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
283 LOG_RTCERR1(StopPlayout, webrtc_channel_);
284 return false;
285 }
286 return true;
287 }
288
289 virtual bool PlaySound(const char *buf, int len, int flags) {
290 // The voe file api is not available in chrome.
291 if (!engine_->voe_sc()->file()) {
292 return false;
293 }
294 // Must stop playing the current sound (if any), because we are about to
295 // modify the stream.
296 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
297 == -1) {
298 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
299 return false;
300 }
301
302 if (buf) {
303 stream_.reset(new WebRtcSoundclipStream(buf, len));
304 stream_->set_loop((flags & SF_LOOP) != 0);
305 stream_->Rewind();
306
307 // Play it.
308 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
309 webrtc_channel_, stream_.get()) == -1) {
310 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
311 LOG(LS_ERROR) << "Unable to start soundclip";
312 return false;
313 }
314 } else {
315 stream_.reset();
316 }
317 return true;
318 }
319
320 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
321
322 private:
323 WebRtcVoiceEngine *engine_;
324 int webrtc_channel_;
325 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
326};
327
328WebRtcVoiceEngine::WebRtcVoiceEngine()
329 : voe_wrapper_(new VoEWrapper()),
330 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000331 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332 tracing_(new VoETraceWrapper()),
333 adm_(NULL),
334 adm_sc_(NULL),
335 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
336 is_dumping_aec_(false),
337 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000338 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339 tx_processor_ssrc_(0),
340 rx_processor_ssrc_(0) {
341 Construct();
342}
343
344WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
345 VoEWrapper* voe_wrapper_sc,
346 VoETraceWrapper* tracing)
347 : voe_wrapper_(voe_wrapper),
348 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000349 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000350 tracing_(tracing),
351 adm_(NULL),
352 adm_sc_(NULL),
353 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
354 is_dumping_aec_(false),
355 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000356 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000357 tx_processor_ssrc_(0),
358 rx_processor_ssrc_(0) {
359 Construct();
360}
361
362void WebRtcVoiceEngine::Construct() {
363 SetTraceFilter(log_filter_);
364 initialized_ = false;
365 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
366 SetTraceOptions("");
367 if (tracing_->SetTraceCallback(this) == -1) {
368 LOG_RTCERR0(SetTraceCallback);
369 }
370 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
371 LOG_RTCERR0(RegisterVoiceEngineObserver);
372 }
373 // Clear the default agc state.
374 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
375
376 // Load our audio codec list.
377 ConstructCodecs();
378
379 // Load our RTP Header extensions.
380 rtp_header_extensions_.push_back(
381 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
382 kRtpAudioLevelHeaderExtensionId));
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000383 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000384
385 // Initialize the VoE Configuration to the default ACM.
386 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
387 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388}
389
390static bool IsOpus(const AudioCodec& codec) {
391 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
392}
393
394static bool IsIsac(const AudioCodec& codec) {
395 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
396}
397
398// True if params["stereo"] == "1"
399static bool IsOpusStereoEnabled(const AudioCodec& codec) {
400 CodecParameterMap::const_iterator param =
401 codec.params.find(kCodecParamStereo);
402 if (param == codec.params.end()) {
403 return false;
404 }
405 return param->second == kParamValueTrue;
406}
407
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000408static bool IsValidOpusBitrate(int bitrate) {
409 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
410}
411
412// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
413// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
414static int GetOpusBitrateFromParams(const AudioCodec& codec) {
415 int bitrate = 0;
416 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
417 return 0;
418 }
419 if (!IsValidOpusBitrate(bitrate)) {
420 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
421 << "invalid value: " << bitrate;
422 return 0;
423 }
424 return bitrate;
425}
426
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000427void WebRtcVoiceEngine::ConstructCodecs() {
428 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
429 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
430 for (int i = 0; i < ncodecs; ++i) {
431 webrtc::CodecInst voe_codec;
432 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
433 // Skip uncompressed formats.
434 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
435 continue;
436 }
437
438 const CodecPref* pref = NULL;
439 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
440 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
441 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
442 kCodecPrefs[j].channels == voe_codec.channels) {
443 pref = &kCodecPrefs[j];
444 break;
445 }
446 }
447
448 if (pref) {
449 // Use the payload type that we've configured in our pref table;
450 // use the offset in our pref table to determine the sort order.
451 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
452 voe_codec.rate, voe_codec.channels,
453 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
454 LOG(LS_INFO) << ToString(codec);
455 if (IsIsac(codec)) {
456 // Indicate auto-bandwidth in signaling.
457 codec.bitrate = 0;
458 }
459 if (IsOpus(codec)) {
460 // Only add fmtp parameters that differ from the spec.
461 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
462 codec.params[kCodecParamMinPTime] =
463 talk_base::ToString(kPreferredMinPTime);
464 }
465 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
466 codec.params[kCodecParamMaxPTime] =
467 talk_base::ToString(kPreferredMaxPTime);
468 }
469 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
470 // when they can be set to values other than the default.
471 }
472 codecs_.push_back(codec);
473 } else {
474 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
475 }
476 }
477 }
478 // Make sure they are in local preference order.
479 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
480}
481
482WebRtcVoiceEngine::~WebRtcVoiceEngine() {
483 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
484 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
485 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
486 }
487 if (adm_) {
488 voe_wrapper_.reset();
489 adm_->Release();
490 adm_ = NULL;
491 }
492 if (adm_sc_) {
493 voe_wrapper_sc_.reset();
494 adm_sc_->Release();
495 adm_sc_ = NULL;
496 }
497
498 // Test to see if the media processor was deregistered properly
499 ASSERT(SignalRxMediaFrame.is_empty());
500 ASSERT(SignalTxMediaFrame.is_empty());
501
502 tracing_->SetTraceCallback(NULL);
503}
504
505bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
506 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
507 bool res = InitInternal();
508 if (res) {
509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
510 } else {
511 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
512 Terminate();
513 }
514 return res;
515}
516
517bool WebRtcVoiceEngine::InitInternal() {
518 // Temporarily turn logging level up for the Init call
519 int old_filter = log_filter_;
520 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
521 SetTraceFilter(extended_filter);
522 SetTraceOptions("");
523
524 // Init WebRtc VoiceEngine.
525 if (voe_wrapper_->base()->Init(adm_) == -1) {
526 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
527 SetTraceFilter(old_filter);
528 return false;
529 }
530
531 SetTraceFilter(old_filter);
532 SetTraceOptions(log_options_);
533
534 // Log the VoiceEngine version info
535 char buffer[1024] = "";
536 voe_wrapper_->base()->GetVersion(buffer);
537 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
538 LogMultiline(talk_base::LS_INFO, buffer);
539
540 // Save the default AGC configuration settings. This must happen before
541 // calling SetOptions or the default will be overwritten.
542 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000543 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000544 return false;
545 }
546
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000547 // Set defaults for options, so that ApplyOptions applies them explicitly
548 // when we clear option (channel) overrides. External clients can still
549 // modify the defaults via SetOptions (on the media engine).
550 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551 return false;
552 }
553
554 // Print our codec list again for the call diagnostic log
555 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
556 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
557 it != codecs_.end(); ++it) {
558 LOG(LS_INFO) << ToString(*it);
559 }
560
wu@webrtc.org4551b792013-10-09 15:37:36 +0000561 // Disable the DTMF playout when a tone is sent.
562 // PlayDtmfTone will be used if local playout is needed.
563 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
564 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
565 }
566
567 initialized_ = true;
568 return true;
569}
570
571bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
572 if (voe_wrapper_sc_initialized_) {
573 return true;
574 }
575 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
576 // be false, so subsequent calls to EnsureSoundclipEngineInit will
577 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578#if defined(LINUX) && !defined(HAVE_LIBPULSE)
579 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
580#endif
581
582 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
583 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
584 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
585 return false;
586 }
587
588 // On Windows, tell it to use the default sound (not communication) devices.
589 // First check whether there is a valid sound device for playback.
590 // TODO(juberti): Clean this up when we support setting the soundclip device.
591#ifdef WIN32
592 // The SetPlayoutDevice may not be implemented in the case of external ADM.
593 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
594 // PeerConnection interface never set the adm_sc_, so need to check both
595 // in order to determine if the external adm is used.
596 if (!adm_ && !adm_sc_) {
597 int num_of_devices = 0;
598 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
599 num_of_devices > 0) {
600 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
601 == -1) {
602 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
603 voe_wrapper_sc_->error());
604 return false;
605 }
606 } else {
607 LOG(LS_WARNING) << "No valid sound playout device found.";
608 }
609 }
610#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000611 voe_wrapper_sc_initialized_ = true;
612 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 return true;
614}
615
616void WebRtcVoiceEngine::Terminate() {
617 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
618 initialized_ = false;
619
620 StopAecDump();
621
wu@webrtc.org4551b792013-10-09 15:37:36 +0000622 if (voe_wrapper_sc_) {
623 voe_wrapper_sc_initialized_ = false;
624 voe_wrapper_sc_->base()->Terminate();
625 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 voe_wrapper_->base()->Terminate();
627 desired_local_monitor_enable_ = false;
628}
629
630int WebRtcVoiceEngine::GetCapabilities() {
631 return AUDIO_SEND | AUDIO_RECV;
632}
633
634VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
635 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
636 if (!ch->valid()) {
637 delete ch;
638 ch = NULL;
639 }
640 return ch;
641}
642
643SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000644 if (!EnsureSoundclipEngineInit()) {
645 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
646 << "initialize.";
647 return NULL;
648 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
650 if (!soundclip->Init() || !soundclip->Enable()) {
651 delete soundclip;
652 return NULL;
653 }
654 return soundclip;
655}
656
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000657bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 if (!ApplyOptions(options)) {
659 return false;
660 }
661 options_ = options;
662 return true;
663}
664
665bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
666 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
667 if (!ApplyOptions(overrides)) {
668 return false;
669 }
670 option_overrides_ = overrides;
671 return true;
672}
673
674bool WebRtcVoiceEngine::ClearOptionOverrides() {
675 LOG(LS_INFO) << "Clearing option overrides.";
676 AudioOptions options = options_;
677 // Only call ApplyOptions if |options_overrides_| contains overrided options.
678 // ApplyOptions affects NS, AGC other options that is shared between
679 // all WebRtcVoiceEngineChannels.
680 if (option_overrides_ == AudioOptions()) {
681 return true;
682 }
683
684 if (!ApplyOptions(options)) {
685 return false;
686 }
687 option_overrides_ = AudioOptions();
688 return true;
689}
690
691// AudioOptions defaults are set in InitInternal (for options with corresponding
692// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
693bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
694 AudioOptions options = options_in; // The options are modified below.
695 // kEcConference is AEC with high suppression.
696 webrtc::EcModes ec_mode = webrtc::kEcConference;
697 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
698 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
699 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
700 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000701 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
702 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
703 << aecm_comfort_noise << " (default is false).";
704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705
706#if defined(IOS)
707 // On iOS, VPIO provides built-in EC and AGC.
708 options.echo_cancellation.Set(false);
709 options.auto_gain_control.Set(false);
710#elif defined(ANDROID)
711 ec_mode = webrtc::kEcAecm;
712#endif
713
714#if defined(IOS) || defined(ANDROID)
715 // Set the AGC mode for iOS as well despite disabling it above, to avoid
716 // unsupported configuration errors from webrtc.
717 agc_mode = webrtc::kAgcFixedDigital;
718 options.typing_detection.Set(false);
719 options.experimental_agc.Set(false);
720 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000721 options.experimental_ns.Set(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722#endif
723
724 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
725
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000726 // Configure whether ACM1 or ACM2 is used.
727 bool enable_acm2 = false;
728 if (options.experimental_acm.Get(&enable_acm2)) {
729 EnableExperimentalAcm(enable_acm2);
730 }
731
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
733
734 bool echo_cancellation;
735 if (options.echo_cancellation.Get(&echo_cancellation)) {
736 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
737 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
738 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000739 } else {
740 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
741 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 }
743#if !defined(ANDROID)
744 // TODO(ajm): Remove the error return on Android from webrtc.
745 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
746 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
747 return false;
748 }
749#endif
750 if (ec_mode == webrtc::kEcAecm) {
751 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
752 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
753 return false;
754 }
755 }
756 }
757
758 bool auto_gain_control;
759 if (options.auto_gain_control.Get(&auto_gain_control)) {
760 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
761 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
762 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000763 } else {
764 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
765 << " with mode " << agc_mode;
766 }
767 }
768
769 if (options.tx_agc_target_dbov.IsSet() ||
770 options.tx_agc_digital_compression_gain.IsSet() ||
771 options.tx_agc_limiter.IsSet()) {
772 // Override default_agc_config_. Generally, an unset option means "leave
773 // the VoE bits alone" in this function, so we want whatever is set to be
774 // stored as the new "default". If we didn't, then setting e.g.
775 // tx_agc_target_dbov would reset digital compression gain and limiter
776 // settings.
777 // Also, if we don't update default_agc_config_, then adjust_agc_delta
778 // would be an offset from the original values, and not whatever was set
779 // explicitly.
780 default_agc_config_.targetLeveldBOv =
781 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
782 default_agc_config_.targetLeveldBOv);
783 default_agc_config_.digitalCompressionGaindB =
784 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
785 default_agc_config_.digitalCompressionGaindB);
786 default_agc_config_.limiterEnable =
787 options.tx_agc_limiter.GetWithDefaultIfUnset(
788 default_agc_config_.limiterEnable);
789 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
790 LOG_RTCERR3(SetAgcConfig,
791 default_agc_config_.targetLeveldBOv,
792 default_agc_config_.digitalCompressionGaindB,
793 default_agc_config_.limiterEnable);
794 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 }
796 }
797
798 bool noise_suppression;
799 if (options.noise_suppression.Get(&noise_suppression)) {
800 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
801 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
802 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000803 } else {
804 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
805 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 }
807 }
808
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000809#ifdef USE_WEBRTC_DEV_BRANCH
810 bool experimental_ns;
811 if (options.experimental_ns.Get(&experimental_ns)) {
812 webrtc::AudioProcessing* audioproc =
813 voe_wrapper_->base()->audio_processing();
814 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
815 // returns NULL on audio_processing().
816 if (audioproc) {
817 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
818 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
819 return false;
820 }
821 } else {
822 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
823 << experimental_ns;
824 }
825 }
826#endif // USE_WEBRTC_DEV_BRANCH
827
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 bool highpass_filter;
829 if (options.highpass_filter.Get(&highpass_filter)) {
830 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
831 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
832 return false;
833 }
834 }
835
836 bool stereo_swapping;
837 if (options.stereo_swapping.Get(&stereo_swapping)) {
838 voep->EnableStereoChannelSwapping(stereo_swapping);
839 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
840 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
841 return false;
842 }
843 }
844
845 bool typing_detection;
846 if (options.typing_detection.Get(&typing_detection)) {
847 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
848 // In case of error, log the info and continue
849 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
850 }
851 }
852
853 int adjust_agc_delta;
854 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
855 if (!AdjustAgcLevel(adjust_agc_delta)) {
856 return false;
857 }
858 }
859
860 bool aec_dump;
861 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000863 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 else
865 StopAecDump();
866 }
867
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000868 bool experimental_aec;
869 if (options.experimental_aec.Get(&experimental_aec)) {
870 webrtc::AudioProcessing* audioproc =
871 voe_wrapper_->base()->audio_processing();
872 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
873 // returns NULL on audio_processing().
874 if (audioproc) {
875 webrtc::Config config;
876 config.Set<webrtc::DelayCorrection>(
877 new webrtc::DelayCorrection(experimental_aec));
878 audioproc->SetExtraOptions(config);
879 }
880 }
881
wu@webrtc.org97077a32013-10-25 21:18:33 +0000882 uint32 recording_sample_rate;
883 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
884 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
885 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
886 }
887 }
888
889 uint32 playout_sample_rate;
890 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
891 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
892 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
893 }
894 }
895
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896
897 return true;
898}
899
900bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
901 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
902 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
903 LOG_RTCERR1(SetDelayOffsetMs, offset);
904 return false;
905 }
906
907 return true;
908}
909
910struct ResumeEntry {
911 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
912 : channel(c),
913 playout(p),
914 send(s) {
915 }
916
917 WebRtcVoiceMediaChannel *channel;
918 bool playout;
919 SendFlags send;
920};
921
922// TODO(juberti): Refactor this so that the core logic can be used to set the
923// soundclip device. At that time, reinstate the soundclip pause/resume code.
924bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
925 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000926#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
928 kDefaultAudioDeviceId;
929 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
930 kDefaultAudioDeviceId;
931 // The device manager uses -1 as the default device, which was the case for
932 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
933#ifndef WIN32
934 if (-1 == in_id) {
935 in_id = kDefaultAudioDeviceId;
936 }
937 if (-1 == out_id) {
938 out_id = kDefaultAudioDeviceId;
939 }
940#endif
941
942 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
943 in_device->name : "Default device";
944 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
945 out_device->name : "Default device";
946 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
947 << ") and speaker to (id=" << out_id << ", name=" << out_name
948 << ")";
949
950 // If we're running the local monitor, we need to stop it first.
951 bool ret = true;
952 if (!PauseLocalMonitor()) {
953 LOG(LS_WARNING) << "Failed to pause local monitor";
954 ret = false;
955 }
956
957 // Must also pause all audio playback and capture.
958 for (ChannelList::const_iterator i = channels_.begin();
959 i != channels_.end(); ++i) {
960 WebRtcVoiceMediaChannel *channel = *i;
961 if (!channel->PausePlayout()) {
962 LOG(LS_WARNING) << "Failed to pause playout";
963 ret = false;
964 }
965 if (!channel->PauseSend()) {
966 LOG(LS_WARNING) << "Failed to pause send";
967 ret = false;
968 }
969 }
970
971 // Find the recording device id in VoiceEngine and set recording device.
972 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
973 ret = false;
974 }
975 if (ret) {
976 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000977 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 ret = false;
979 }
980 }
981
982 // Find the playout device id in VoiceEngine and set playout device.
983 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
984 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
985 ret = false;
986 }
987 if (ret) {
988 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000989 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990 ret = false;
991 }
992 }
993
994 // Resume all audio playback and capture.
995 for (ChannelList::const_iterator i = channels_.begin();
996 i != channels_.end(); ++i) {
997 WebRtcVoiceMediaChannel *channel = *i;
998 if (!channel->ResumePlayout()) {
999 LOG(LS_WARNING) << "Failed to resume playout";
1000 ret = false;
1001 }
1002 if (!channel->ResumeSend()) {
1003 LOG(LS_WARNING) << "Failed to resume send";
1004 ret = false;
1005 }
1006 }
1007
1008 // Resume local monitor.
1009 if (!ResumeLocalMonitor()) {
1010 LOG(LS_WARNING) << "Failed to resume local monitor";
1011 ret = false;
1012 }
1013
1014 if (ret) {
1015 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1016 << ") and speaker to (id="<< out_id << " name=" << out_name
1017 << ")";
1018 }
1019
1020 return ret;
1021#else
1022 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001023#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024}
1025
1026bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1027 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1028 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001029#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 *rtc_id = dev_id;
1031 return true;
1032#else
1033 // In Windows and Mac, we need to find the VoiceEngine device id by name
1034 // unless the input dev_id is the default device id.
1035 if (kDefaultAudioDeviceId == dev_id) {
1036 *rtc_id = dev_id;
1037 return true;
1038 }
1039
1040 // Get the number of VoiceEngine audio devices.
1041 int count = 0;
1042 if (is_input) {
1043 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1044 LOG_RTCERR0(GetNumOfRecordingDevices);
1045 return false;
1046 }
1047 } else {
1048 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1049 LOG_RTCERR0(GetNumOfPlayoutDevices);
1050 return false;
1051 }
1052 }
1053
1054 for (int i = 0; i < count; ++i) {
1055 char name[128];
1056 char guid[128];
1057 if (is_input) {
1058 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1059 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1060 } else {
1061 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1062 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1063 }
1064
1065 std::string webrtc_name(name);
1066 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1067 *rtc_id = i;
1068 return true;
1069 }
1070 }
1071 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1072 return false;
1073#endif
1074}
1075
1076bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1077 unsigned int ulevel;
1078 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1079 LOG_RTCERR1(GetSpeakerVolume, level);
1080 return false;
1081 }
1082 *level = ulevel;
1083 return true;
1084}
1085
1086bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1087 ASSERT(level >= 0 && level <= 255);
1088 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1089 LOG_RTCERR1(SetSpeakerVolume, level);
1090 return false;
1091 }
1092 return true;
1093}
1094
1095int WebRtcVoiceEngine::GetInputLevel() {
1096 unsigned int ulevel;
1097 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1098 static_cast<int>(ulevel) : -1;
1099}
1100
1101bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1102 desired_local_monitor_enable_ = enable;
1103 return ChangeLocalMonitor(desired_local_monitor_enable_);
1104}
1105
1106bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1107 // The voe file api is not available in chrome.
1108 if (!voe_wrapper_->file()) {
1109 return false;
1110 }
1111 if (enable && !monitor_) {
1112 monitor_.reset(new WebRtcMonitorStream);
1113 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1114 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1115 // Must call Stop() because there are some cases where Start will report
1116 // failure but still change the state, and if we leave VE in the on state
1117 // then it could crash later when trying to invoke methods on our monitor.
1118 voe_wrapper_->file()->StopRecordingMicrophone();
1119 monitor_.reset();
1120 return false;
1121 }
1122 } else if (!enable && monitor_) {
1123 voe_wrapper_->file()->StopRecordingMicrophone();
1124 monitor_.reset();
1125 }
1126 return true;
1127}
1128
1129bool WebRtcVoiceEngine::PauseLocalMonitor() {
1130 return ChangeLocalMonitor(false);
1131}
1132
1133bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1134 return ChangeLocalMonitor(desired_local_monitor_enable_);
1135}
1136
1137const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1138 return codecs_;
1139}
1140
1141bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1142 return FindWebRtcCodec(in, NULL);
1143}
1144
1145// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1146bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1147 webrtc::CodecInst* out) {
1148 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1149 for (int i = 0; i < ncodecs; ++i) {
1150 webrtc::CodecInst voe_codec;
1151 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1152 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1153 voe_codec.rate, voe_codec.channels, 0);
1154 bool multi_rate = IsCodecMultiRate(voe_codec);
1155 // Allow arbitrary rates for ISAC to be specified.
1156 if (multi_rate) {
1157 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1158 codec.bitrate = 0;
1159 }
1160 if (codec.Matches(in)) {
1161 if (out) {
1162 // Fixup the payload type.
1163 voe_codec.pltype = in.id;
1164
1165 // Set bitrate if specified.
1166 if (multi_rate && in.bitrate != 0) {
1167 voe_codec.rate = in.bitrate;
1168 }
1169
1170 // Apply codec-specific settings.
1171 if (IsIsac(codec)) {
1172 // If ISAC and an explicit bitrate is not specified,
1173 // enable auto bandwidth adjustment.
1174 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1175 }
1176 *out = voe_codec;
1177 }
1178 return true;
1179 }
1180 }
1181 }
1182 return false;
1183}
1184const std::vector<RtpHeaderExtension>&
1185WebRtcVoiceEngine::rtp_header_extensions() const {
1186 return rtp_header_extensions_;
1187}
1188
1189void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1190 // if min_sev == -1, we keep the current log level.
1191 if (min_sev >= 0) {
1192 SetTraceFilter(SeverityToFilter(min_sev));
1193 }
1194 log_options_ = filter;
1195 SetTraceOptions(initialized_ ? log_options_ : "");
1196}
1197
1198int WebRtcVoiceEngine::GetLastEngineError() {
1199 return voe_wrapper_->error();
1200}
1201
1202void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1203 log_filter_ = filter;
1204 tracing_->SetTraceFilter(filter);
1205}
1206
1207// We suppport three different logging settings for VoiceEngine:
1208// 1. Observer callback that goes into talk diagnostic logfile.
1209// Use --logfile and --loglevel
1210//
1211// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1212// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1213//
1214// 3. EC log and dump for debugging QualityEngine.
1215// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1216//
1217// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1218// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1219void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1220 // Set encrypted trace file.
1221 std::vector<std::string> opts;
1222 talk_base::tokenize(options, ' ', '"', '"', &opts);
1223 std::vector<std::string>::iterator tracefile =
1224 std::find(opts.begin(), opts.end(), "tracefile");
1225 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1226 // Write encrypted debug output (at same loglevel) to file
1227 // EncryptedTraceFile no longer supported.
1228 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1229 LOG_RTCERR1(SetTraceFile, *tracefile);
1230 }
1231 }
1232
wu@webrtc.org97077a32013-10-25 21:18:33 +00001233 // Allow trace options to override the trace filter. We default
1234 // it to log_filter_ (as a translation of libjingle log levels)
1235 // elsewhere, but this allows clients to explicitly set webrtc
1236 // log levels.
1237 std::vector<std::string>::iterator tracefilter =
1238 std::find(opts.begin(), opts.end(), "tracefilter");
1239 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1240 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1241 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1242 }
1243 }
1244
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 // Set AEC dump file
1246 std::vector<std::string>::iterator recordEC =
1247 std::find(opts.begin(), opts.end(), "recordEC");
1248 if (recordEC != opts.end()) {
1249 ++recordEC;
1250 if (recordEC != opts.end())
1251 StartAecDump(recordEC->c_str());
1252 else
1253 StopAecDump();
1254 }
1255}
1256
1257// Ignore spammy trace messages, mostly from the stats API when we haven't
1258// gotten RTCP info yet from the remote side.
1259bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1260 static const char* kTracesToIgnore[] = {
1261 "\tfailed to GetReportBlockInformation",
1262 "GetRecCodec() failed to get received codec",
1263 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1264 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1265 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1266 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1267 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1268 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1269 "SenderInfoReceived No received SR",
1270 "StatisticsRTP() no statistics available",
1271 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1272 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1273 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1274 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1275 NULL
1276 };
1277 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1278 if (trace.find(*p) != std::string::npos) {
1279 return true;
1280 }
1281 }
1282 return false;
1283}
1284
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001285void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1286 if (enable == use_experimental_acm_)
1287 return;
1288 if (enable) {
1289 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1290 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1291 new webrtc::NewAudioCodingModuleFactory());
1292 } else {
1293 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1294 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1295 new webrtc::AudioCodingModuleFactory());
1296 }
1297 use_experimental_acm_ = enable;
1298}
1299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1301 int length) {
1302 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1303 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1304 sev = talk_base::LS_ERROR;
1305 else if (level == webrtc::kTraceWarning)
1306 sev = talk_base::LS_WARNING;
1307 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1308 sev = talk_base::LS_INFO;
1309 else if (level == webrtc::kTraceTerseInfo)
1310 sev = talk_base::LS_INFO;
1311
1312 // Skip past boilerplate prefix text
1313 if (length < 72) {
1314 std::string msg(trace, length);
1315 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1316 LOG_V(sev) << msg;
1317 } else {
1318 std::string msg(trace + 71, length - 72);
1319 if (!ShouldIgnoreTrace(msg)) {
1320 LOG_V(sev) << "webrtc: " << msg;
1321 }
1322 }
1323}
1324
1325void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1326 talk_base::CritScope lock(&channels_cs_);
1327 WebRtcVoiceMediaChannel* channel = NULL;
1328 uint32 ssrc = 0;
1329 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1330 << channel_num << ".";
1331 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1332 ASSERT(channel != NULL);
1333 channel->OnError(ssrc, err_code);
1334 } else {
1335 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1336 << " could not be found in channel list when error reported.";
1337 }
1338}
1339
1340bool WebRtcVoiceEngine::FindChannelAndSsrc(
1341 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1342 ASSERT(channel != NULL && ssrc != NULL);
1343
1344 *channel = NULL;
1345 *ssrc = 0;
1346 // Find corresponding channel and ssrc
1347 for (ChannelList::const_iterator it = channels_.begin();
1348 it != channels_.end(); ++it) {
1349 ASSERT(*it != NULL);
1350 if ((*it)->FindSsrc(channel_num, ssrc)) {
1351 *channel = *it;
1352 return true;
1353 }
1354 }
1355
1356 return false;
1357}
1358
1359// This method will search through the WebRtcVoiceMediaChannels and
1360// obtain the voice engine's channel number.
1361bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1362 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1363 ASSERT(channel_num != NULL);
1364 ASSERT(direction == MPD_RX || direction == MPD_TX);
1365
1366 *channel_num = -1;
1367 // Find corresponding channel for ssrc.
1368 for (ChannelList::const_iterator it = channels_.begin();
1369 it != channels_.end(); ++it) {
1370 ASSERT(*it != NULL);
1371 if (direction & MPD_RX) {
1372 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1373 }
1374 if (*channel_num == -1 && (direction & MPD_TX)) {
1375 *channel_num = (*it)->GetSendChannelNum(ssrc);
1376 }
1377 if (*channel_num != -1) {
1378 return true;
1379 }
1380 }
1381 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1382 return false;
1383}
1384
1385void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1386 talk_base::CritScope lock(&channels_cs_);
1387 channels_.push_back(channel);
1388}
1389
1390void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1391 talk_base::CritScope lock(&channels_cs_);
1392 ChannelList::iterator i = std::find(channels_.begin(),
1393 channels_.end(),
1394 channel);
1395 if (i != channels_.end()) {
1396 channels_.erase(i);
1397 }
1398}
1399
1400void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401 soundclips_.push_back(soundclip);
1402}
1403
1404void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1405 SoundclipList::iterator i = std::find(soundclips_.begin(),
1406 soundclips_.end(),
1407 soundclip);
1408 if (i != soundclips_.end()) {
1409 soundclips_.erase(i);
1410 }
1411}
1412
1413// Adjusts the default AGC target level by the specified delta.
1414// NB: If we start messing with other config fields, we'll want
1415// to save the current webrtc::AgcConfig as well.
1416bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1417 webrtc::AgcConfig config = default_agc_config_;
1418 config.targetLeveldBOv -= delta;
1419
1420 LOG(LS_INFO) << "Adjusting AGC level from default -"
1421 << default_agc_config_.targetLeveldBOv << "dB to -"
1422 << config.targetLeveldBOv << "dB";
1423
1424 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1425 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1426 return false;
1427 }
1428 return true;
1429}
1430
1431bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1432 webrtc::AudioDeviceModule* adm_sc) {
1433 if (initialized_) {
1434 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1435 return false;
1436 }
1437 if (adm_) {
1438 adm_->Release();
1439 adm_ = NULL;
1440 }
1441 if (adm) {
1442 adm_ = adm;
1443 adm_->AddRef();
1444 }
1445
1446 if (adm_sc_) {
1447 adm_sc_->Release();
1448 adm_sc_ = NULL;
1449 }
1450 if (adm_sc) {
1451 adm_sc_ = adm_sc;
1452 adm_sc_->AddRef();
1453 }
1454 return true;
1455}
1456
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001457bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1458 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1459 if (!aec_dump_file_stream) {
1460 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1461 if (!talk_base::ClosePlatformFile(file))
1462 LOG(LS_WARNING) << "Could not close file.";
1463 return false;
1464 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001465 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001466 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001467 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001468 LOG_RTCERR0(StartDebugRecording);
1469 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001470 return false;
1471 }
1472 is_dumping_aec_ = true;
1473 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476bool WebRtcVoiceEngine::RegisterProcessor(
1477 uint32 ssrc,
1478 VoiceProcessor* voice_processor,
1479 MediaProcessorDirection direction) {
1480 bool register_with_webrtc = false;
1481 int channel_id = -1;
1482 bool success = false;
1483 uint32* processor_ssrc = NULL;
1484 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1485 if (voice_processor == NULL || !found_channel) {
1486 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1487 << " foundChannel: " << found_channel;
1488 return false;
1489 }
1490
1491 webrtc::ProcessingTypes processing_type;
1492 {
1493 talk_base::CritScope cs(&signal_media_critical_);
1494 if (direction == MPD_RX) {
1495 processing_type = webrtc::kPlaybackAllChannelsMixed;
1496 if (SignalRxMediaFrame.is_empty()) {
1497 register_with_webrtc = true;
1498 processor_ssrc = &rx_processor_ssrc_;
1499 }
1500 SignalRxMediaFrame.connect(voice_processor,
1501 &VoiceProcessor::OnFrame);
1502 } else {
1503 processing_type = webrtc::kRecordingPerChannel;
1504 if (SignalTxMediaFrame.is_empty()) {
1505 register_with_webrtc = true;
1506 processor_ssrc = &tx_processor_ssrc_;
1507 }
1508 SignalTxMediaFrame.connect(voice_processor,
1509 &VoiceProcessor::OnFrame);
1510 }
1511 }
1512 if (register_with_webrtc) {
1513 // TODO(janahan): when registering consider instantiating a
1514 // a VoeMediaProcess object and not make the engine extend the interface.
1515 if (voe()->media() && voe()->media()->
1516 RegisterExternalMediaProcessing(channel_id,
1517 processing_type,
1518 *this) != -1) {
1519 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1520 << channel_id;
1521 *processor_ssrc = ssrc;
1522 success = true;
1523 } else {
1524 LOG_RTCERR2(RegisterExternalMediaProcessing,
1525 channel_id,
1526 processing_type);
1527 success = false;
1528 }
1529 } else {
1530 // If we don't have to register with the engine, we just needed to
1531 // connect a new processor, set success to true;
1532 success = true;
1533 }
1534 return success;
1535}
1536
1537bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1538 MediaProcessorDirection channel_direction,
1539 uint32 ssrc,
1540 VoiceProcessor* voice_processor,
1541 MediaProcessorDirection processor_direction) {
1542 bool success = true;
1543 FrameSignal* signal;
1544 webrtc::ProcessingTypes processing_type;
1545 uint32* processor_ssrc = NULL;
1546 if (channel_direction == MPD_RX) {
1547 signal = &SignalRxMediaFrame;
1548 processing_type = webrtc::kPlaybackAllChannelsMixed;
1549 processor_ssrc = &rx_processor_ssrc_;
1550 } else {
1551 signal = &SignalTxMediaFrame;
1552 processing_type = webrtc::kRecordingPerChannel;
1553 processor_ssrc = &tx_processor_ssrc_;
1554 }
1555
1556 int deregister_id = -1;
1557 {
1558 talk_base::CritScope cs(&signal_media_critical_);
1559 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1560 signal->disconnect(voice_processor);
1561 int channel_id = -1;
1562 bool found_channel = FindChannelNumFromSsrc(ssrc,
1563 channel_direction,
1564 &channel_id);
1565 if (signal->is_empty() && found_channel) {
1566 deregister_id = channel_id;
1567 }
1568 }
1569 }
1570 if (deregister_id != -1) {
1571 if (voe()->media() &&
1572 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1573 processing_type) != -1) {
1574 *processor_ssrc = 0;
1575 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1576 << deregister_id;
1577 } else {
1578 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1579 deregister_id,
1580 processing_type);
1581 success = false;
1582 }
1583 }
1584 return success;
1585}
1586
1587bool WebRtcVoiceEngine::UnregisterProcessor(
1588 uint32 ssrc,
1589 VoiceProcessor* voice_processor,
1590 MediaProcessorDirection direction) {
1591 bool success = true;
1592 if (voice_processor == NULL) {
1593 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1594 << ssrc;
1595 return false;
1596 }
1597 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1598 success = false;
1599 }
1600 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1601 success = false;
1602 }
1603 return success;
1604}
1605
1606// Implementing method from WebRtc VoEMediaProcess interface
1607// Do not lock mux_channel_cs_ in this callback.
1608void WebRtcVoiceEngine::Process(int channel,
1609 webrtc::ProcessingTypes type,
1610 int16_t audio10ms[],
1611 int length,
1612 int sampling_freq,
1613 bool is_stereo) {
1614 talk_base::CritScope cs(&signal_media_critical_);
1615 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1616 if (type == webrtc::kPlaybackAllChannelsMixed) {
1617 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1618 } else if (type == webrtc::kRecordingPerChannel) {
1619 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1620 } else {
1621 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1622 << " channel: " << channel << " type: " << type
1623 << " tx_ssrc: " << tx_processor_ssrc_
1624 << " rx_ssrc: " << rx_processor_ssrc_;
1625 }
1626}
1627
1628void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1629 if (!is_dumping_aec_) {
1630 // Start dumping AEC when we are not dumping.
1631 if (voe_wrapper_->processing()->StartDebugRecording(
1632 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001633 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 } else {
1635 is_dumping_aec_ = true;
1636 }
1637 }
1638}
1639
1640void WebRtcVoiceEngine::StopAecDump() {
1641 if (is_dumping_aec_) {
1642 // Stop dumping AEC when we are dumping.
1643 if (voe_wrapper_->processing()->StopDebugRecording() !=
1644 webrtc::AudioProcessing::kNoError) {
1645 LOG_RTCERR0(StopDebugRecording);
1646 }
1647 is_dumping_aec_ = false;
1648 }
1649}
1650
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001651int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001652 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001653}
1654
1655int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1656 return CreateVoiceChannel(voe_wrapper_.get());
1657}
1658
1659int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1660 return CreateVoiceChannel(voe_wrapper_sc_.get());
1661}
1662
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001663class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1664 : public AudioRenderer::Sink {
1665 public:
1666 WebRtcVoiceChannelRenderer(int ch,
1667 webrtc::AudioTransport* voe_audio_transport)
1668 : channel_(ch),
1669 voe_audio_transport_(voe_audio_transport),
1670 renderer_(NULL) {
1671 }
1672 virtual ~WebRtcVoiceChannelRenderer() {
1673 Stop();
1674 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001675
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001676 // Starts the rendering by setting a sink to the renderer to get data
1677 // callback.
1678 // TODO(xians): Make sure Start() is called only once.
1679 void Start(AudioRenderer* renderer) {
1680 ASSERT(renderer != NULL);
xians@webrtc.orgef221512014-02-21 10:31:29 +00001681 if (renderer_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001682 ASSERT(renderer_ == renderer);
1683 return;
1684 }
1685
1686 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1687 // in getUserMedia by default.
1688 renderer->AddChannel(channel_);
1689 renderer->SetSink(this);
1690 renderer_ = renderer;
1691 }
1692
1693 // Stops rendering by setting the sink of the renderer to NULL. No data
1694 // callback will be received after this method.
1695 void Stop() {
xians@webrtc.orgef221512014-02-21 10:31:29 +00001696 if (!renderer_)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001697 return;
1698
1699 renderer_->RemoveChannel(channel_);
1700 renderer_->SetSink(NULL);
1701 renderer_ = NULL;
1702 }
1703
1704 // AudioRenderer::Sink implementation.
1705 virtual void OnData(const void* audio_data,
1706 int bits_per_sample,
1707 int sample_rate,
1708 int number_of_channels,
1709 int number_of_frames) OVERRIDE {
xians@webrtc.orgef221512014-02-21 10:31:29 +00001710 // TODO(xians): Make new interface in AudioTransport to pass the data to
1711 // WebRtc VoE channel.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001712 }
1713
1714 // Accessor to the VoE channel ID.
1715 int channel() const { return channel_; }
1716
1717 private:
1718 const int channel_;
1719 webrtc::AudioTransport* const voe_audio_transport_;
1720
1721 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1722 // PeerConnection will make sure invalidating the pointer before the object
1723 // goes away.
1724 AudioRenderer* renderer_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001725};
1726
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001727// WebRtcVoiceMediaChannel
1728WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1729 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1730 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001731 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001732 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001733 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734 options_(),
1735 dtmf_allowed_(false),
1736 desired_playout_(false),
1737 nack_enabled_(false),
1738 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001739 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740 desired_send_(SEND_NOTHING),
1741 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 default_receive_ssrc_(0) {
1743 engine->RegisterChannel(this);
1744 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1745 << voe_channel();
1746
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001747 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001748}
1749
1750WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1751 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1752 << voe_channel();
1753
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001754 // Remove any remaining send streams, the default channel will be deleted
1755 // later.
1756 while (!send_channels_.empty())
1757 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758
1759 // Unregister ourselves from the engine.
1760 engine()->UnregisterChannel(this);
1761 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001762 while (!receive_channels_.empty()) {
1763 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 }
1765
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001766 // Delete the default channel.
1767 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768}
1769
1770bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1771 LOG(LS_INFO) << "Setting voice channel options: "
1772 << options.ToString();
1773
wu@webrtc.orgde305012013-10-31 15:40:38 +00001774 // Check if DSCP value is changed from previous.
1775 bool dscp_option_changed = (options_.dscp != options.dscp);
1776
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001777 // TODO(xians): Add support to set different options for different send
1778 // streams after we support multiple APMs.
1779
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780 // We retain all of the existing options, and apply the given ones
1781 // on top. This means there is no way to "clear" options such that
1782 // they go back to the engine default.
1783 options_.SetAll(options);
1784
1785 if (send_ != SEND_NOTHING) {
1786 if (!engine()->SetOptionOverrides(options_)) {
1787 LOG(LS_WARNING) <<
1788 "Failed to engine SetOptionOverrides during channel SetOptions.";
1789 return false;
1790 }
1791 } else {
1792 // Will be interpreted when appropriate.
1793 }
1794
wu@webrtc.org97077a32013-10-25 21:18:33 +00001795 // Receiver-side auto gain control happens per channel, so set it here from
1796 // options. Note that, like conference mode, setting it on the engine won't
1797 // have the desired effect, since voice channels don't inherit options from
1798 // the media engine when those options are applied per-channel.
1799 bool rx_auto_gain_control;
1800 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1801 if (engine()->voe()->processing()->SetRxAgcStatus(
1802 voe_channel(), rx_auto_gain_control,
1803 webrtc::kAgcFixedDigital) == -1) {
1804 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1805 return false;
1806 } else {
1807 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1808 << " with mode " << webrtc::kAgcFixedDigital;
1809 }
1810 }
1811 if (options.rx_agc_target_dbov.IsSet() ||
1812 options.rx_agc_digital_compression_gain.IsSet() ||
1813 options.rx_agc_limiter.IsSet()) {
1814 webrtc::AgcConfig config;
1815 // If only some of the options are being overridden, get the current
1816 // settings for the channel and bail if they aren't available.
1817 if (!options.rx_agc_target_dbov.IsSet() ||
1818 !options.rx_agc_digital_compression_gain.IsSet() ||
1819 !options.rx_agc_limiter.IsSet()) {
1820 if (engine()->voe()->processing()->GetRxAgcConfig(
1821 voe_channel(), config) != 0) {
1822 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1823 << "channel " << voe_channel() << ". Since not all rx "
1824 << "agc options are specified, unable to safely set rx "
1825 << "agc options.";
1826 return false;
1827 }
1828 }
1829 config.targetLeveldBOv =
1830 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1831 config.targetLeveldBOv);
1832 config.digitalCompressionGaindB =
1833 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1834 config.digitalCompressionGaindB);
1835 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1836 config.limiterEnable);
1837 if (engine()->voe()->processing()->SetRxAgcConfig(
1838 voe_channel(), config) == -1) {
1839 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1840 config.digitalCompressionGaindB, config.limiterEnable);
1841 return false;
1842 }
1843 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001844 if (dscp_option_changed) {
1845 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001846 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001847 dscp = kAudioDscpValue;
1848 if (MediaChannel::SetDscp(dscp) != 0) {
1849 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1850 }
1851 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001852
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853 LOG(LS_INFO) << "Set voice channel options. Current options: "
1854 << options_.ToString();
1855 return true;
1856}
1857
1858bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1859 const std::vector<AudioCodec>& codecs) {
1860 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 LOG(LS_INFO) << "Setting receive voice codecs:";
1862
1863 std::vector<AudioCodec> new_codecs;
1864 // Find all new codecs. We allow adding new codecs but don't allow changing
1865 // the payload type of codecs that is already configured since we might
1866 // already be receiving packets with that payload type.
1867 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001868 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001869 AudioCodec old_codec;
1870 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1871 if (old_codec.id != it->id) {
1872 LOG(LS_ERROR) << it->name << " payload type changed.";
1873 return false;
1874 }
1875 } else {
1876 new_codecs.push_back(*it);
1877 }
1878 }
1879 if (new_codecs.empty()) {
1880 // There are no new codecs to configure. Already configured codecs are
1881 // never removed.
1882 return true;
1883 }
1884
1885 if (playout_) {
1886 // Receive codecs can not be changed while playing. So we temporarily
1887 // pause playout.
1888 PausePlayout();
1889 }
1890
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001891 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1893 it != new_codecs.end() && ret; ++it) {
1894 webrtc::CodecInst voe_codec;
1895 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1896 LOG(LS_INFO) << ToString(*it);
1897 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001898 if (default_receive_ssrc_ == 0) {
1899 // Set the receive codecs on the default channel explicitly if the
1900 // default channel is not used by |receive_channels_|, this happens in
1901 // conference mode or in non-conference mode when there is no playout
1902 // channel.
1903 // TODO(xians): Figure out how we use the default channel in conference
1904 // mode.
1905 if (engine()->voe()->codec()->SetRecPayloadType(
1906 voe_channel(), voe_codec) == -1) {
1907 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1908 ret = false;
1909 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 }
1911
1912 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001913 for (ChannelMap::iterator it = receive_channels_.begin();
1914 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001916 it->second->channel(), voe_codec) == -1) {
1917 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001918 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919 ret = false;
1920 }
1921 }
1922 } else {
1923 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1924 ret = false;
1925 }
1926 }
1927 if (ret) {
1928 recv_codecs_ = codecs;
1929 }
1930
1931 if (desired_playout_ && !playout_) {
1932 ResumePlayout();
1933 }
1934 return ret;
1935}
1936
1937bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001938 int channel, const std::vector<AudioCodec>& codecs) {
1939 // Disable VAD, and FEC unless we know the other side wants them.
1940 engine()->voe()->codec()->SetVADStatus(channel, false);
1941 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1942 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943
1944 // Scan through the list to figure out the codec to use for sending, along
1945 // with the proper configuration for VAD and DTMF.
1946 bool first = true;
1947 webrtc::CodecInst send_codec;
1948 memset(&send_codec, 0, sizeof(send_codec));
1949
1950 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1951 it != codecs.end(); ++it) {
1952 // Ignore codecs we don't know about. The negotiation step should prevent
1953 // this, but double-check to be sure.
1954 webrtc::CodecInst voe_codec;
1955 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001956 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 continue;
1958 }
1959
1960 // If OPUS, change what we send according to the "stereo" codec
1961 // parameter, and not the "channels" parameter. We set
1962 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1963 // the bitrate is not specified, i.e. is zero, we set it to the
1964 // appropriate default value for mono or stereo Opus.
1965 if (IsOpus(*it)) {
1966 if (IsOpusStereoEnabled(*it)) {
1967 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001968 if (!IsValidOpusBitrate(it->bitrate)) {
1969 if (it->bitrate != 0) {
1970 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1971 << it->bitrate
1972 << ") with default opus stereo bitrate: "
1973 << kOpusStereoBitrate;
1974 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 voe_codec.rate = kOpusStereoBitrate;
1976 }
1977 } else {
1978 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001979 if (!IsValidOpusBitrate(it->bitrate)) {
1980 if (it->bitrate != 0) {
1981 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1982 << it->bitrate
1983 << ") with default opus mono bitrate: "
1984 << kOpusMonoBitrate;
1985 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 voe_codec.rate = kOpusMonoBitrate;
1987 }
1988 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001989 int bitrate_from_params = GetOpusBitrateFromParams(*it);
1990 if (bitrate_from_params != 0) {
1991 voe_codec.rate = bitrate_from_params;
1992 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 }
1994
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001995 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1996 // about it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1998 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001999 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2000 channel, it->id) == -1) {
2001 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2002 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 }
2005
2006 // Turn voice activity detection/comfort noise on if supported.
2007 // Set the wideband CN payload type appropriately.
2008 // (narrowband always uses the static payload type 13).
2009 if (_stricmp(it->name.c_str(), "CN") == 0) {
2010 webrtc::PayloadFrequencies cn_freq;
2011 switch (it->clockrate) {
2012 case 8000:
2013 cn_freq = webrtc::kFreq8000Hz;
2014 break;
2015 case 16000:
2016 cn_freq = webrtc::kFreq16000Hz;
2017 break;
2018 case 32000:
2019 cn_freq = webrtc::kFreq32000Hz;
2020 break;
2021 default:
2022 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2023 << " not supported.";
2024 continue;
2025 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002026 // Set the CN payloadtype and the VAD status.
2027 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2028 if (cn_freq != webrtc::kFreq8000Hz) {
2029 if (engine()->voe()->codec()->SetSendCNPayloadType(
2030 channel, it->id, cn_freq) == -1) {
2031 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2032 // TODO(ajm): This failure condition will be removed from VoE.
2033 // Restore the return here when we update to a new enough webrtc.
2034 //
2035 // Not returning false because the SetSendCNPayloadType will fail if
2036 // the channel is already sending.
2037 // This can happen if the remote description is applied twice, for
2038 // example in the case of ROAP on top of JSEP, where both side will
2039 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002041 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002042
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002043 // Only turn on VAD if we have a CN payload type that matches the
2044 // clockrate for the codec we are going to use.
2045 if (it->clockrate == send_codec.plfreq) {
2046 LOG(LS_INFO) << "Enabling VAD";
2047 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2048 LOG_RTCERR2(SetVADStatus, channel, true);
2049 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050 }
2051 }
2052 }
2053
2054 // We'll use the first codec in the list to actually send audio data.
2055 // Be sure to use the payload type requested by the remote side.
2056 // "red", for FEC audio, is a special case where the actual codec to be
2057 // used is specified in params.
2058 if (first) {
2059 if (_stricmp(it->name.c_str(), "red") == 0) {
2060 // Parse out the RED parameters. If we fail, just ignore RED;
2061 // we don't support all possible params/usage scenarios.
2062 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2063 continue;
2064 }
2065
2066 // Enable redundant encoding of the specified codec. Treat any
2067 // failure as a fatal internal error.
2068 LOG(LS_INFO) << "Enabling FEC";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002069 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2070 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2071 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 }
2073 } else {
2074 send_codec = voe_codec;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002075 nack_enabled_ = IsNackEnabled(*it);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002076 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 }
2078 first = false;
2079 // Set the codec immediately, since SetVADStatus() depends on whether
2080 // the current codec is mono or stereo.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002081 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002082 return false;
2083 }
2084 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085
2086 // If we're being asked to set an empty list of codecs, due to a buggy client,
2087 // choose the most common format: PCMU
2088 if (first) {
2089 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
2090 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
2091 engine()->FindWebRtcCodec(codec, &send_codec);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002092 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093 return false;
2094 }
2095
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002096 // Always update the |send_codec_| to the currently set send codec.
2097 send_codec_.reset(new webrtc::CodecInst(send_codec));
2098
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002099 if (send_bw_setting_) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002100 SetSendBandwidthInternal(send_bw_bps_);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002101 }
2102
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002103 return true;
2104}
2105
2106bool WebRtcVoiceMediaChannel::SetSendCodecs(
2107 const std::vector<AudioCodec>& codecs) {
2108 dtmf_allowed_ = false;
2109 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2110 it != codecs.end(); ++it) {
2111 // Find the DTMF telephone event "codec".
2112 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2113 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2114 dtmf_allowed_ = true;
2115 }
2116 }
2117
2118 // Cache the codecs in order to configure the channel created later.
2119 send_codecs_ = codecs;
2120 for (ChannelMap::iterator iter = send_channels_.begin();
2121 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002122 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002123 return false;
2124 }
2125 }
2126
2127 SetNack(receive_channels_, nack_enabled_);
2128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 return true;
2130}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002131
2132void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2133 bool nack_enabled) {
2134 for (ChannelMap::const_iterator it = channels.begin();
2135 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002136 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002137 }
2138}
2139
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002140void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002142 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2144 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002145 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2147 }
2148}
2149
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150bool WebRtcVoiceMediaChannel::SetSendCodec(
2151 const webrtc::CodecInst& send_codec) {
2152 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2153 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002154 for (ChannelMap::iterator iter = send_channels_.begin();
2155 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002156 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002157 return false;
2158 }
2159
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002160 return true;
2161}
2162
2163bool WebRtcVoiceMediaChannel::SetSendCodec(
2164 int channel, const webrtc::CodecInst& send_codec) {
2165 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2166 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2167
2168 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2169 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170 return false;
2171 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 return true;
2173}
2174
2175bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2176 const std::vector<RtpHeaderExtension>& extensions) {
2177 // We don't support any incoming extensions headers right now.
2178 return true;
2179}
2180
2181bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2182 const std::vector<RtpHeaderExtension>& extensions) {
2183 // Enable the audio level extension header if requested.
2184 std::vector<RtpHeaderExtension>::const_iterator it;
2185 for (it = extensions.begin(); it != extensions.end(); ++it) {
2186 if (it->uri == kRtpAudioLevelHeaderExtension) {
2187 break;
2188 }
2189 }
2190
2191 bool enable = (it != extensions.end());
2192 int id = 0;
2193
2194 if (enable) {
2195 id = it->id;
2196 if (id < kMinRtpHeaderExtensionId ||
2197 id > kMaxRtpHeaderExtensionId) {
2198 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2199 return false;
2200 }
2201 }
2202
2203 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002204 for (ChannelMap::const_iterator iter = send_channels_.begin();
2205 iter != send_channels_.end(); ++iter) {
2206 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002207 iter->second->channel(), enable, id) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002208 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002209 iter->second->channel(), enable, id);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002210 return false;
2211 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002212 }
2213
2214 return true;
2215}
2216
2217bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2218 desired_playout_ = playout;
2219 return ChangePlayout(desired_playout_);
2220}
2221
2222bool WebRtcVoiceMediaChannel::PausePlayout() {
2223 return ChangePlayout(false);
2224}
2225
2226bool WebRtcVoiceMediaChannel::ResumePlayout() {
2227 return ChangePlayout(desired_playout_);
2228}
2229
2230bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2231 if (playout_ == playout) {
2232 return true;
2233 }
2234
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002235 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002237 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238 // Only toggle the default channel if we don't have any other channels.
2239 result = SetPlayout(voe_channel(), playout);
2240 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002241 for (ChannelMap::iterator it = receive_channels_.begin();
2242 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002243 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002244 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002245 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 result = false;
2247 }
2248 }
2249
2250 if (result) {
2251 playout_ = playout;
2252 }
2253 return result;
2254}
2255
2256bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2257 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002258 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 return ChangeSend(desired_send_);
2260 return true;
2261}
2262
2263bool WebRtcVoiceMediaChannel::PauseSend() {
2264 return ChangeSend(SEND_NOTHING);
2265}
2266
2267bool WebRtcVoiceMediaChannel::ResumeSend() {
2268 return ChangeSend(desired_send_);
2269}
2270
2271bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2272 if (send_ == send) {
2273 return true;
2274 }
2275
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002276 // Change the settings on each send channel.
2277 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 engine()->SetOptionOverrides(options_);
2279
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002280 // Change the settings on each send channel.
2281 for (ChannelMap::iterator iter = send_channels_.begin();
2282 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002283 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002286
2287 // Clear up the options after stopping sending.
2288 if (send == SEND_NOTHING)
2289 engine()->ClearOptionOverrides();
2290
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002291 send_ = send;
2292 return true;
2293}
2294
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002295bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2296 if (send == SEND_MICROPHONE) {
2297 if (engine()->voe()->base()->StartSend(channel) == -1) {
2298 LOG_RTCERR1(StartSend, channel);
2299 return false;
2300 }
2301 if (engine()->voe()->file() &&
2302 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2303 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2304 return false;
2305 }
2306 } else { // SEND_NOTHING
2307 ASSERT(send == SEND_NOTHING);
2308 if (engine()->voe()->base()->StopSend(channel) == -1) {
2309 LOG_RTCERR1(StopSend, channel);
2310 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 }
2312 }
2313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314 return true;
2315}
2316
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002317void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2318 if (engine()->voe()->network()->RegisterExternalTransport(
2319 channel, *this) == -1) {
2320 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2321 }
2322
2323 // Enable RTCP (for quality stats and feedback messages)
2324 EnableRtcp(channel);
2325
2326 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2327 ResetRecvCodecs(channel);
2328}
2329
2330bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2331 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2332 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2333 }
2334
2335 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2336 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 return false;
2338 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002339
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002340 return true;
2341}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002342
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002343bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2344 // If the default channel is already used for sending create a new channel
2345 // otherwise use the default channel for sending.
2346 int channel = GetSendChannelNum(sp.first_ssrc());
2347 if (channel != -1) {
2348 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2349 return false;
2350 }
2351
2352 bool default_channel_is_available = true;
2353 for (ChannelMap::const_iterator iter = send_channels_.begin();
2354 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002355 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002356 default_channel_is_available = false;
2357 break;
2358 }
2359 }
2360 if (default_channel_is_available) {
2361 channel = voe_channel();
2362 } else {
2363 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002364 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002365 if (channel == -1) {
2366 LOG_RTCERR0(CreateChannel);
2367 return false;
2368 }
2369
2370 ConfigureSendChannel(channel);
2371 }
2372
2373 // Save the channel to send_channels_, so that RemoveSendStream() can still
2374 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002375#ifdef USE_WEBRTC_DEV_BRANCH
2376 webrtc::AudioTransport* audio_transport =
2377 engine()->voe()->base()->audio_transport();
2378#else
2379 webrtc::AudioTransport* audio_transport = NULL;
2380#endif
2381 send_channels_.insert(std::make_pair(
2382 sp.first_ssrc(),
2383 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002384
2385 // Set the send (local) SSRC.
2386 // If there are multiple send SSRCs, we can only set the first one here, and
2387 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2388 // (with a codec requires multiple SSRC(s)).
2389 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2390 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2391 return false;
2392 }
2393
2394 // At this point the channel's local SSRC has been updated. If the channel is
2395 // the default channel make sure that all the receive channels are updated as
2396 // well. Receive channels have to have the same SSRC as the default channel in
2397 // order to send receiver reports with this SSRC.
2398 if (IsDefaultChannel(channel)) {
2399 for (ChannelMap::const_iterator it = receive_channels_.begin();
2400 it != receive_channels_.end(); ++it) {
2401 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002402 if (!IsDefaultChannel(it->second->channel())) {
2403 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002404 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002405 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002406 return false;
2407 }
2408 }
2409 }
2410 }
2411
2412 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2413 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2414 return false;
2415 }
2416
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002417 // Set the current codecs to be used for the new channel.
2418 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419 return false;
2420
2421 return ChangeSend(channel, desired_send_);
2422}
2423
2424bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2425 ChannelMap::iterator it = send_channels_.find(ssrc);
2426 if (it == send_channels_.end()) {
2427 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2428 << " which doesn't exist.";
2429 return false;
2430 }
2431
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002432 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002433 ChangeSend(channel, SEND_NOTHING);
2434
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002435 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2436 // this will disconnect the audio renderer with the send channel.
2437 delete it->second;
2438 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002439
2440 if (IsDefaultChannel(channel)) {
2441 // Do not delete the default channel since the receive channels depend on
2442 // the default channel, recycle it instead.
2443 ChangeSend(channel, SEND_NOTHING);
2444 } else {
2445 // Clean up and delete the send channel.
2446 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2447 << " with VoiceEngine channel #" << channel << ".";
2448 if (!DeleteChannel(channel))
2449 return false;
2450 }
2451
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002452 if (send_channels_.empty())
2453 ChangeSend(SEND_NOTHING);
2454
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002455 return true;
2456}
2457
2458bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002459 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460
2461 if (!VERIFY(sp.ssrcs.size() == 1))
2462 return false;
2463 uint32 ssrc = sp.first_ssrc();
2464
wu@webrtc.org78187522013-10-07 23:32:02 +00002465 if (ssrc == 0) {
2466 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2467 return false;
2468 }
2469
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002470 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2471 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 return false;
2473 }
2474
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002475 // Reuse default channel for recv stream in non-conference mode call
2476 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002477#ifdef USE_WEBRTC_DEV_BRANCH
2478 webrtc::AudioTransport* audio_transport =
2479 engine()->voe()->base()->audio_transport();
2480#else
2481 webrtc::AudioTransport* audio_transport = NULL;
2482#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002483 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2484 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2485 << " reuse default channel";
2486 default_receive_ssrc_ = sp.first_ssrc();
2487 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002488 default_receive_ssrc_,
2489 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002490 return SetPlayout(voe_channel(), playout_);
2491 }
2492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002494 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 if (channel == -1) {
2496 LOG_RTCERR0(CreateChannel);
2497 return false;
2498 }
2499
wu@webrtc.org78187522013-10-07 23:32:02 +00002500 if (!ConfigureRecvChannel(channel)) {
2501 DeleteChannel(channel);
2502 return false;
2503 }
2504
2505 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002506 std::make_pair(
2507 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002508
2509 LOG(LS_INFO) << "New audio stream " << ssrc
2510 << " registered to VoiceEngine channel #"
2511 << channel << ".";
2512 return true;
2513}
2514
2515bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 // Configure to use external transport, like our default channel.
2517 if (engine()->voe()->network()->RegisterExternalTransport(
2518 channel, *this) == -1) {
2519 LOG_RTCERR2(SetExternalTransport, channel, this);
2520 return false;
2521 }
2522
2523 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002524 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002525 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2526 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002527 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 return false;
2529 }
2530 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002531 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532 return false;
2533 }
2534
2535 // Use the same recv payload types as our default channel.
2536 ResetRecvCodecs(channel);
2537 if (!recv_codecs_.empty()) {
2538 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2539 it != recv_codecs_.end(); ++it) {
2540 webrtc::CodecInst voe_codec;
2541 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2542 voe_codec.pltype = it->id;
2543 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2544 if (engine()->voe()->codec()->GetRecPayloadType(
2545 voe_channel(), voe_codec) != -1) {
2546 if (engine()->voe()->codec()->SetRecPayloadType(
2547 channel, voe_codec) == -1) {
2548 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2549 return false;
2550 }
2551 }
2552 }
2553 }
2554 }
2555
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002556 if (InConferenceMode()) {
2557 // To be in par with the video, voe_channel() is not used for receiving in
2558 // a conference call.
2559 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2560 // This is the first stream in a multi user meeting. We can now
2561 // disable playback of the default stream. This since the default
2562 // stream will probably have received some initial packets before
2563 // the new stream was added. This will mean that the CN state from
2564 // the default channel will be mixed in with the other streams
2565 // throughout the whole meeting, which might be disturbing.
2566 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2567 SetPlayout(voe_channel(), false);
2568 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002570 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002572 return SetPlayout(channel, playout_);
2573}
2574
2575bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002576 talk_base::CritScope lock(&receive_channels_cs_);
2577 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002578 if (it == receive_channels_.end()) {
2579 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2580 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002581 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002582 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002584 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2585 // will disconnect the audio renderer with the receive channel.
2586 // Cache the channel before the deletion.
2587 const int channel = it->second->channel();
2588 delete it->second;
2589 receive_channels_.erase(it);
2590
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002591 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002592 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002593 // Recycle the default channel is for recv stream.
2594 if (playout_)
2595 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002597 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002598 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002600
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002601 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002602 << " with VoiceEngine channel #" << channel << ".";
2603 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002604 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002605
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002606 bool enable_default_channel_playout = false;
2607 if (receive_channels_.empty()) {
2608 // The last stream was removed. We can now enable the default
2609 // channel for new channels to be played out immediately without
2610 // waiting for AddStream messages.
2611 // We do this for both conference mode and non-conference mode.
2612 // TODO(oja): Does the default channel still have it's CN state?
2613 enable_default_channel_playout = true;
2614 }
2615 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2616 default_receive_ssrc_ != 0) {
2617 // Only the default channel is active, enable the playout on default
2618 // channel.
2619 enable_default_channel_playout = true;
2620 }
2621 if (enable_default_channel_playout && playout_) {
2622 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2623 SetPlayout(voe_channel(), true);
2624 }
2625
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002626 return true;
2627}
2628
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002629bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2630 AudioRenderer* renderer) {
2631 ChannelMap::iterator it = receive_channels_.find(ssrc);
2632 if (it == receive_channels_.end()) {
2633 if (renderer) {
2634 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002635 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002636 return false;
2637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002639 // The channel likely has gone away, do nothing.
2640 return true;
2641 }
2642
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002643 if (renderer)
2644 it->second->Start(renderer);
2645 else
2646 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002647
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002648 return true;
2649}
2650
2651bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2652 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002653 ChannelMap::iterator it = send_channels_.find(ssrc);
2654 if (it == send_channels_.end()) {
2655 if (renderer) {
2656 // Return an error if trying to set a valid renderer with an invalid ssrc.
2657 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2658 return false;
2659 }
2660
2661 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002662 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002663 }
2664
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002665 if (renderer)
2666 it->second->Start(renderer);
2667 else
2668 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670 return true;
2671}
2672
2673bool WebRtcVoiceMediaChannel::GetActiveStreams(
2674 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002675 // In conference mode, the default channel should not be in
2676 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 for (ChannelMap::iterator it = receive_channels_.begin();
2679 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002680 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002681 if (level > 0) {
2682 actives->push_back(std::make_pair(it->first, level));
2683 }
2684 }
2685 return true;
2686}
2687
2688int WebRtcVoiceMediaChannel::GetOutputLevel() {
2689 // return the highest output level of all streams
2690 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 for (ChannelMap::iterator it = receive_channels_.begin();
2692 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002693 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 highest = talk_base::_max(level, highest);
2695 }
2696 return highest;
2697}
2698
2699int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2700 int ret;
2701 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2702 // In case of error, log the info and continue
2703 LOG_RTCERR0(TimeSinceLastTyping);
2704 ret = -1;
2705 } else {
2706 ret *= 1000; // We return ms, webrtc returns seconds.
2707 }
2708 return ret;
2709}
2710
2711void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2712 int cost_per_typing, int reporting_threshold, int penalty_decay,
2713 int type_event_delay) {
2714 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2715 time_window, cost_per_typing,
2716 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2717 // In case of error, log the info and continue
2718 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2719 cost_per_typing, reporting_threshold, penalty_decay,
2720 type_event_delay);
2721 }
2722}
2723
2724bool WebRtcVoiceMediaChannel::SetOutputScaling(
2725 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002726 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002727 // Collect the channels to scale the output volume.
2728 std::vector<int> channels;
2729 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002730 // Default channel is not in receive_channels_ if it is not being used for
2731 // playout.
2732 if (default_receive_ssrc_ == 0)
2733 channels.push_back(voe_channel());
2734 for (ChannelMap::const_iterator it = receive_channels_.begin();
2735 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002736 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 }
2738 } else { // Collect only the channel of the specified ssrc.
2739 int channel = GetReceiveChannelNum(ssrc);
2740 if (-1 == channel) {
2741 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2742 return false;
2743 }
2744 channels.push_back(channel);
2745 }
2746
2747 // Scale the output volume for the collected channels. We first normalize to
2748 // scale the volume and then set the left and right pan.
2749 float scale = static_cast<float>(talk_base::_max(left, right));
2750 if (scale > 0.0001f) {
2751 left /= scale;
2752 right /= scale;
2753 }
2754 for (std::vector<int>::const_iterator it = channels.begin();
2755 it != channels.end(); ++it) {
2756 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2757 *it, scale)) {
2758 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2759 return false;
2760 }
2761 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2762 *it, static_cast<float>(left), static_cast<float>(right))) {
2763 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2764 // Do not return if fails. SetOutputVolumePan is not available for all
2765 // pltforms.
2766 }
2767 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2768 << " right=" << right * scale
2769 << " for channel " << *it << " and ssrc " << ssrc;
2770 }
2771 return true;
2772}
2773
2774bool WebRtcVoiceMediaChannel::GetOutputScaling(
2775 uint32 ssrc, double* left, double* right) {
2776 if (!left || !right) return false;
2777
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002778 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 // Determine which channel based on ssrc.
2780 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2781 if (channel == -1) {
2782 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2783 return false;
2784 }
2785
2786 float scaling;
2787 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2788 channel, scaling)) {
2789 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2790 return false;
2791 }
2792
2793 float left_pan;
2794 float right_pan;
2795 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2796 channel, left_pan, right_pan)) {
2797 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2798 // If GetOutputVolumePan fails, we use the default left and right pan.
2799 left_pan = 1.0f;
2800 right_pan = 1.0f;
2801 }
2802
2803 *left = scaling * left_pan;
2804 *right = scaling * right_pan;
2805 return true;
2806}
2807
2808bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2809 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2810 return true;
2811}
2812
2813bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2814 bool play, bool loop) {
2815 if (!ringback_tone_) {
2816 return false;
2817 }
2818
2819 // The voe file api is not available in chrome.
2820 if (!engine()->voe()->file()) {
2821 return false;
2822 }
2823
2824 // Determine which VoiceEngine channel to play on.
2825 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2826 if (channel == -1) {
2827 return false;
2828 }
2829
2830 // Make sure the ringtone is cued properly, and play it out.
2831 if (play) {
2832 ringback_tone_->set_loop(loop);
2833 ringback_tone_->Rewind();
2834 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2835 ringback_tone_.get()) == -1) {
2836 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2837 LOG(LS_ERROR) << "Unable to start ringback tone";
2838 return false;
2839 }
2840 ringback_channels_.insert(channel);
2841 LOG(LS_INFO) << "Started ringback on channel " << channel;
2842 } else {
2843 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2844 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2845 LOG_RTCERR1(StopPlayingFileLocally, channel);
2846 return false;
2847 }
2848 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2849 ringback_channels_.erase(channel);
2850 }
2851
2852 return true;
2853}
2854
2855bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2856 return dtmf_allowed_;
2857}
2858
2859bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2860 int duration, int flags) {
2861 if (!dtmf_allowed_) {
2862 return false;
2863 }
2864
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 // Send the event.
2866 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002867 int channel = -1;
2868 if (ssrc == 0) {
2869 bool default_channel_is_inuse = false;
2870 for (ChannelMap::const_iterator iter = send_channels_.begin();
2871 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002872 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002873 default_channel_is_inuse = true;
2874 break;
2875 }
2876 }
2877 if (default_channel_is_inuse) {
2878 channel = voe_channel();
2879 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002880 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002881 }
2882 } else {
2883 channel = GetSendChannelNum(ssrc);
2884 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002885 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2887 << ssrc << " is not in use.";
2888 return false;
2889 }
2890 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002891 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2892 channel, event, true, duration) == -1) {
2893 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002894 return false;
2895 }
2896 }
2897
2898 // Play the event.
2899 if (flags & cricket::DF_PLAY) {
2900 // Play DTMF tone locally.
2901 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2902 LOG_RTCERR2(PlayDtmfTone, event, duration);
2903 return false;
2904 }
2905 }
2906
2907 return true;
2908}
2909
wu@webrtc.orga9890802013-12-13 00:21:03 +00002910void WebRtcVoiceMediaChannel::OnPacketReceived(
2911 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 // Pick which channel to send this packet to. If this packet doesn't match
2913 // any multiplexed streams, just send it to the default channel. Otherwise,
2914 // send it to the specific decoder instance for that stream.
2915 int which_channel = GetReceiveChannelNum(
2916 ParseSsrc(packet->data(), packet->length(), false));
2917 if (which_channel == -1) {
2918 which_channel = voe_channel();
2919 }
2920
2921 // Stop any ringback that might be playing on the channel.
2922 // It's possible the ringback has already stopped, ih which case we'll just
2923 // use the opportunity to remove the channel from ringback_channels_.
2924 if (engine()->voe()->file()) {
2925 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2926 if (it != ringback_channels_.end()) {
2927 if (engine()->voe()->file()->IsPlayingFileLocally(
2928 which_channel) == 1) {
2929 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2930 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2931 << " due to incoming media";
2932 }
2933 ringback_channels_.erase(which_channel);
2934 }
2935 }
2936
2937 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002938 engine()->voe()->network()->ReceivedRTPPacket(
2939 which_channel,
2940 packet->data(),
2941 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942}
2943
wu@webrtc.orga9890802013-12-13 00:21:03 +00002944void WebRtcVoiceMediaChannel::OnRtcpReceived(
2945 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002946 // Sending channels need all RTCP packets with feedback information.
2947 // Even sender reports can contain attached report blocks.
2948 // Receiving channels need sender reports in order to create
2949 // correct receiver reports.
2950 int type = 0;
2951 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2952 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2953 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 }
2955
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002956 // If it is a sender report, find the channel that is listening.
2957 bool has_sent_to_default_channel = false;
2958 if (type == kRtcpTypeSR) {
2959 int which_channel = GetReceiveChannelNum(
2960 ParseSsrc(packet->data(), packet->length(), true));
2961 if (which_channel != -1) {
2962 engine()->voe()->network()->ReceivedRTCPPacket(
2963 which_channel,
2964 packet->data(),
2965 static_cast<unsigned int>(packet->length()));
2966
2967 if (IsDefaultChannel(which_channel))
2968 has_sent_to_default_channel = true;
2969 }
2970 }
2971
2972 // SR may continue RR and any RR entry may correspond to any one of the send
2973 // channels. So all RTCP packets must be forwarded all send channels. VoE
2974 // will filter out RR internally.
2975 for (ChannelMap::iterator iter = send_channels_.begin();
2976 iter != send_channels_.end(); ++iter) {
2977 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002978 if (IsDefaultChannel(iter->second->channel()) &&
2979 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002980 continue;
2981
2982 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002983 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002984 packet->data(),
2985 static_cast<unsigned int>(packet->length()));
2986 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987}
2988
2989bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002990 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2991 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2993 return false;
2994 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002995 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2996 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 return false;
2998 }
2999 return true;
3000}
3001
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003002bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3003 // TODO(andresp): Add support for setting an independent start bandwidth when
3004 // bandwidth estimation is enabled for voice engine.
3005 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003006}
3007
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003008bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3009 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3010
3011 return SetSendBandwidthInternal(bps);
3012}
3013
3014bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3015 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3016
3017 send_bw_setting_ = true;
3018 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003020 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003021 LOG(LS_INFO) << "The send codec has not been set up yet. "
3022 << "The send bandwidth setting will be applied later.";
3023 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024 }
3025
3026 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003027 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3028 // SetMaxSendBandwith(0), the second call removes the previous limit.
3029 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 return true;
3031
3032 webrtc::CodecInst codec = *send_codec_;
3033 bool is_multi_rate = IsCodecMultiRate(codec);
3034
3035 if (is_multi_rate) {
3036 // If codec is multi-rate then just set the bitrate.
3037 codec.rate = bps;
3038 if (!SetSendCodec(codec)) {
3039 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3040 << " to bitrate " << bps << " bps.";
3041 return false;
3042 }
3043 return true;
3044 } else {
3045 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3046 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3047 // fixed bitrate then ignore.
3048 if (bps < codec.rate) {
3049 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3050 << " to bitrate " << bps << " bps"
3051 << ", requires at least " << codec.rate << " bps.";
3052 return false;
3053 }
3054 return true;
3055 }
3056}
3057
3058bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003059 bool echo_metrics_on = false;
3060 // These can take on valid negative values, so use the lowest possible level
3061 // as default rather than -1.
3062 int echo_return_loss = -100;
3063 int echo_return_loss_enhancement = -100;
3064 // These can also be negative, but in practice -1 is only used to signal
3065 // insufficient data, since the resolution is limited to multiples of 4 ms.
3066 int echo_delay_median_ms = -1;
3067 int echo_delay_std_ms = -1;
3068 if (engine()->voe()->processing()->GetEcMetricsStatus(
3069 echo_metrics_on) != -1 && echo_metrics_on) {
3070 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3071 // here, but it appears to be unsuitable currently. Revisit after this is
3072 // investigated: http://b/issue?id=5666755
3073 int erl, erle, rerl, anlp;
3074 if (engine()->voe()->processing()->GetEchoMetrics(
3075 erl, erle, rerl, anlp) != -1) {
3076 echo_return_loss = erl;
3077 echo_return_loss_enhancement = erle;
3078 }
3079
3080 int median, std;
3081 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3082 echo_delay_median_ms = median;
3083 echo_delay_std_ms = std;
3084 }
3085 }
3086
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003087 webrtc::CallStatistics cs;
3088 unsigned int ssrc;
3089 webrtc::CodecInst codec;
3090 unsigned int level;
3091
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003092 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3093 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003094 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003095
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003096 // Fill in the sender info, based on what we know, and what the
3097 // remote side told us it got from its RTCP report.
3098 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003099
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003100 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3101 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3102 continue;
3103 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003105 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003106 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3107 sinfo.bytes_sent = cs.bytesSent;
3108 sinfo.packets_sent = cs.packetsSent;
3109 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3110 // returns 0 to indicate an error value.
3111 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3112
3113 // Get data from the last remote RTCP report. Use default values if no data
3114 // available.
3115 sinfo.fraction_lost = -1.0;
3116 sinfo.jitter_ms = -1;
3117 sinfo.packets_lost = -1;
3118 sinfo.ext_seqnum = -1;
3119 std::vector<webrtc::ReportBlock> receive_blocks;
3120 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3121 channel, &receive_blocks) != -1 &&
3122 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3123 std::vector<webrtc::ReportBlock>::iterator iter;
3124 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3125 ++iter) {
3126 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003127 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003128 // Convert Q8 to floating point.
3129 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3130 // Convert samples to milliseconds.
3131 if (codec.plfreq / 1000 > 0) {
3132 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3133 }
3134 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3135 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3136 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 }
3139 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003140
3141 // Local speech level.
3142 sinfo.audio_level = (engine()->voe()->volume()->
3143 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3144
3145 // TODO(xians): We are injecting the same APM logging to all the send
3146 // channels here because there is no good way to know which send channel
3147 // is using the APM. The correct fix is to allow the send channels to have
3148 // their own APM so that we can feed the correct APM logging to different
3149 // send channels. See issue crbug/264611 .
3150 sinfo.echo_return_loss = echo_return_loss;
3151 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3152 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3153 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003154 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3155 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003156 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003157
3158 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003159 }
3160
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003161 // Build the list of receivers, one for each receiving channel, or 1 in
3162 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003164 for (ChannelMap::const_iterator it = receive_channels_.begin();
3165 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003166 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167 }
3168 if (channels.empty()) {
3169 channels.push_back(voe_channel());
3170 }
3171
3172 // Get the SSRC and stats for each receiver, based on our own calculations.
3173 for (std::vector<int>::const_iterator it = channels.begin();
3174 it != channels.end(); ++it) {
3175 memset(&cs, 0, sizeof(cs));
3176 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3177 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3178 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3179 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003180 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181 rinfo.bytes_rcvd = cs.bytesReceived;
3182 rinfo.packets_rcvd = cs.packetsReceived;
3183 // The next four fields are from the most recently sent RTCP report.
3184 // Convert Q8 to floating point.
3185 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3186 rinfo.packets_lost = cs.cumulativeLost;
3187 rinfo.ext_seqnum = cs.extendedMax;
3188 // Convert samples to milliseconds.
3189 if (codec.plfreq / 1000 > 0) {
3190 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3191 }
3192
3193 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3194 webrtc::NetworkStatistics ns;
3195 if (engine()->voe()->neteq() &&
3196 engine()->voe()->neteq()->GetNetworkStatistics(
3197 *it, ns) != -1) {
3198 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3199 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3200 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003201 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003203
3204 webrtc::AudioDecodingCallStats ds;
3205 if (engine()->voe()->neteq() &&
3206 engine()->voe()->neteq()->GetDecodingCallStatistics(
3207 *it, &ds) != -1) {
3208 rinfo.decoding_calls_to_silence_generator =
3209 ds.calls_to_silence_generator;
3210 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3211 rinfo.decoding_normal = ds.decoded_normal;
3212 rinfo.decoding_plc = ds.decoded_plc;
3213 rinfo.decoding_cng = ds.decoded_cng;
3214 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3215 }
3216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003218 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219 int playout_buffer_delay_ms = 0;
3220 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003221 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3222 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3223 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224 }
3225
3226 // Get speech level.
3227 rinfo.audio_level = (engine()->voe()->volume()->
3228 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3229 info->receivers.push_back(rinfo);
3230 }
3231 }
3232
3233 return true;
3234}
3235
3236void WebRtcVoiceMediaChannel::GetLastMediaError(
3237 uint32* ssrc, VoiceMediaChannel::Error* error) {
3238 ASSERT(ssrc != NULL);
3239 ASSERT(error != NULL);
3240 FindSsrc(voe_channel(), ssrc);
3241 *error = WebRtcErrorToChannelError(GetLastEngineError());
3242}
3243
3244bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003245 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003247 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3249 // This means the error is not limited to a specific channel. Signal the
3250 // message using ssrc=0. If the current channel is sending, use this
3251 // channel for sending the message.
3252 *ssrc = 0;
3253 return true;
3254 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003255 // Check whether this is a sending channel.
3256 for (ChannelMap::const_iterator it = send_channels_.begin();
3257 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003258 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003259 // This is a sending channel.
3260 uint32 local_ssrc = 0;
3261 if (engine()->voe()->rtp()->GetLocalSSRC(
3262 channel_num, local_ssrc) != -1) {
3263 *ssrc = local_ssrc;
3264 }
3265 return true;
3266 }
3267 }
3268
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003270 for (ChannelMap::const_iterator it = receive_channels_.begin();
3271 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003272 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273 *ssrc = it->first;
3274 return true;
3275 }
3276 }
3277 }
3278 return false;
3279}
3280
3281void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003282 if (error == VE_TYPING_NOISE_WARNING) {
3283 typing_noise_detected_ = true;
3284 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3285 typing_noise_detected_ = false;
3286 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3288}
3289
3290int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3291 unsigned int ulevel;
3292 int ret =
3293 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3294 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3295}
3296
3297int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003298 ChannelMap::iterator it = receive_channels_.find(ssrc);
3299 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003300 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3302}
3303
3304int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003305 ChannelMap::iterator it = send_channels_.find(ssrc);
3306 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003307 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003308
3309 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310}
3311
3312bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3313 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3314 // Get the RED encodings from the parameter with no name. This may
3315 // change based on what is discussed on the Jingle list.
3316 // The encoding parameter is of the form "a/b"; we only support where
3317 // a == b. Verify this and parse out the value into red_pt.
3318 // If the parameter value is absent (as it will be until we wire up the
3319 // signaling of this message), use the second codec specified (i.e. the
3320 // one after "red") as the encoding parameter.
3321 int red_pt = -1;
3322 std::string red_params;
3323 CodecParameterMap::const_iterator it = red_codec.params.find("");
3324 if (it != red_codec.params.end()) {
3325 red_params = it->second;
3326 std::vector<std::string> red_pts;
3327 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3328 red_pts[0] != red_pts[1] ||
3329 !talk_base::FromString(red_pts[0], &red_pt)) {
3330 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3331 return false;
3332 }
3333 } else if (red_codec.params.empty()) {
3334 LOG(LS_WARNING) << "RED params not present, using defaults";
3335 if (all_codecs.size() > 1) {
3336 red_pt = all_codecs[1].id;
3337 }
3338 }
3339
3340 // Try to find red_pt in |codecs|.
3341 std::vector<AudioCodec>::const_iterator codec;
3342 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3343 if (codec->id == red_pt)
3344 break;
3345 }
3346
3347 // If we find the right codec, that will be the codec we pass to
3348 // SetSendCodec, with the desired payload type.
3349 if (codec != all_codecs.end() &&
3350 engine()->FindWebRtcCodec(*codec, send_codec)) {
3351 } else {
3352 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3353 return false;
3354 }
3355
3356 return true;
3357}
3358
3359bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3360 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003361 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362 return false;
3363 }
3364 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3365 // what we want to do with them.
3366 // engine()->voe().EnableVQMon(voe_channel(), true);
3367 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3368 return true;
3369}
3370
3371bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3372 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3373 for (int i = 0; i < ncodecs; ++i) {
3374 webrtc::CodecInst voe_codec;
3375 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3376 voe_codec.pltype = -1;
3377 if (engine()->voe()->codec()->SetRecPayloadType(
3378 channel, voe_codec) == -1) {
3379 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3380 return false;
3381 }
3382 }
3383 }
3384 return true;
3385}
3386
3387bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3388 if (playout) {
3389 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3390 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3391 LOG_RTCERR1(StartPlayout, channel);
3392 return false;
3393 }
3394 } else {
3395 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3396 engine()->voe()->base()->StopPlayout(channel);
3397 }
3398 return true;
3399}
3400
3401uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3402 bool rtcp) {
3403 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3404 uint32 ssrc = 0;
3405 if (len >= (ssrc_pos + sizeof(ssrc))) {
3406 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3407 }
3408 return ssrc;
3409}
3410
3411// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3412VoiceMediaChannel::Error
3413 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3414 switch (err_code) {
3415 case 0:
3416 return ERROR_NONE;
3417 case VE_CANNOT_START_RECORDING:
3418 case VE_MIC_VOL_ERROR:
3419 case VE_GET_MIC_VOL_ERROR:
3420 case VE_CANNOT_ACCESS_MIC_VOL:
3421 return ERROR_REC_DEVICE_OPEN_FAILED;
3422 case VE_SATURATION_WARNING:
3423 return ERROR_REC_DEVICE_SATURATION;
3424 case VE_REC_DEVICE_REMOVED:
3425 return ERROR_REC_DEVICE_REMOVED;
3426 case VE_RUNTIME_REC_WARNING:
3427 case VE_RUNTIME_REC_ERROR:
3428 return ERROR_REC_RUNTIME_ERROR;
3429 case VE_CANNOT_START_PLAYOUT:
3430 case VE_SPEAKER_VOL_ERROR:
3431 case VE_GET_SPEAKER_VOL_ERROR:
3432 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3433 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3434 case VE_RUNTIME_PLAY_WARNING:
3435 case VE_RUNTIME_PLAY_ERROR:
3436 return ERROR_PLAY_RUNTIME_ERROR;
3437 case VE_TYPING_NOISE_WARNING:
3438 return ERROR_REC_TYPING_NOISE_DETECTED;
3439 default:
3440 return VoiceMediaChannel::ERROR_OTHER;
3441 }
3442}
3443
3444int WebRtcSoundclipStream::Read(void *buf, int len) {
3445 size_t res = 0;
3446 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003447 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003448}
3449
3450int WebRtcSoundclipStream::Rewind() {
3451 mem_.Rewind();
3452 // Return -1 to keep VoiceEngine from looping.
3453 return (loop_) ? 0 : -1;
3454}
3455
3456} // namespace cricket
3457
3458#endif // HAVE_WEBRTC_VOICE