blob: c3b090e086d494ce2a33f32a7599b97cad7fb5cd [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
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000197static bool IsTelephoneEventCodec(const std::string& name) {
198 return _stricmp(name.c_str(), "telephone-event") == 0;
199}
200
201static bool IsCNCodec(const std::string& name) {
202 return _stricmp(name.c_str(), "CN") == 0;
203}
204
205static bool IsRedCodec(const std::string& name) {
206 return _stricmp(name.c_str(), "red") == 0;
207}
208
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209static bool FindCodec(const std::vector<AudioCodec>& codecs,
210 const AudioCodec& codec,
211 AudioCodec* found_codec) {
212 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
213 it != codecs.end(); ++it) {
214 if (it->Matches(codec)) {
215 if (found_codec != NULL) {
216 *found_codec = *it;
217 }
218 return true;
219 }
220 }
221 return false;
222}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224static bool IsNackEnabled(const AudioCodec& codec) {
225 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
226 kParamValueEmpty));
227}
228
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000229// Gets the default set of options applied to the engine. Historically, these
230// were supplied as a combination of flags from the channel manager (ec, agc,
231// ns, and highpass) and the rest hardcoded in InitInternal.
232static AudioOptions GetDefaultEngineOptions() {
233 AudioOptions options;
234 options.echo_cancellation.Set(true);
235 options.auto_gain_control.Set(true);
236 options.noise_suppression.Set(true);
237 options.highpass_filter.Set(true);
238 options.stereo_swapping.Set(false);
239 options.typing_detection.Set(true);
240 options.conference_mode.Set(false);
241 options.adjust_agc_delta.Set(0);
242 options.experimental_agc.Set(false);
243 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000244 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000245 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000246 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000247 return options;
248}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249
250class WebRtcSoundclipMedia : public SoundclipMedia {
251 public:
252 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
253 : engine_(engine), webrtc_channel_(-1) {
254 engine_->RegisterSoundclip(this);
255 }
256
257 virtual ~WebRtcSoundclipMedia() {
258 engine_->UnregisterSoundclip(this);
259 if (webrtc_channel_ != -1) {
260 // We shouldn't have to call Disable() here. DeleteChannel() should call
261 // StopPlayout() while deleting the channel. We should fix the bug
262 // inside WebRTC and remove the Disable() call bellow. This work is
263 // tracked by bug http://b/issue?id=5382855.
264 PlaySound(NULL, 0, 0);
265 Disable();
266 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
267 == -1) {
268 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
269 }
270 }
271 }
272
273 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000274 if (!engine_->voe_sc()) {
275 return false;
276 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000277 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278 if (webrtc_channel_ == -1) {
279 LOG_RTCERR0(CreateChannel);
280 return false;
281 }
282 return true;
283 }
284
285 bool Enable() {
286 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
287 LOG_RTCERR1(StartPlayout, webrtc_channel_);
288 return false;
289 }
290 return true;
291 }
292
293 bool Disable() {
294 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
295 LOG_RTCERR1(StopPlayout, webrtc_channel_);
296 return false;
297 }
298 return true;
299 }
300
301 virtual bool PlaySound(const char *buf, int len, int flags) {
302 // The voe file api is not available in chrome.
303 if (!engine_->voe_sc()->file()) {
304 return false;
305 }
306 // Must stop playing the current sound (if any), because we are about to
307 // modify the stream.
308 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
309 == -1) {
310 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
311 return false;
312 }
313
314 if (buf) {
315 stream_.reset(new WebRtcSoundclipStream(buf, len));
316 stream_->set_loop((flags & SF_LOOP) != 0);
317 stream_->Rewind();
318
319 // Play it.
320 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
321 webrtc_channel_, stream_.get()) == -1) {
322 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
323 LOG(LS_ERROR) << "Unable to start soundclip";
324 return false;
325 }
326 } else {
327 stream_.reset();
328 }
329 return true;
330 }
331
332 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
333
334 private:
335 WebRtcVoiceEngine *engine_;
336 int webrtc_channel_;
337 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
338};
339
340WebRtcVoiceEngine::WebRtcVoiceEngine()
341 : voe_wrapper_(new VoEWrapper()),
342 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000343 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000344 tracing_(new VoETraceWrapper()),
345 adm_(NULL),
346 adm_sc_(NULL),
347 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
348 is_dumping_aec_(false),
349 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000350 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 tx_processor_ssrc_(0),
352 rx_processor_ssrc_(0) {
353 Construct();
354}
355
356WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
357 VoEWrapper* voe_wrapper_sc,
358 VoETraceWrapper* tracing)
359 : voe_wrapper_(voe_wrapper),
360 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000361 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000362 tracing_(tracing),
363 adm_(NULL),
364 adm_sc_(NULL),
365 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
366 is_dumping_aec_(false),
367 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000368 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369 tx_processor_ssrc_(0),
370 rx_processor_ssrc_(0) {
371 Construct();
372}
373
374void WebRtcVoiceEngine::Construct() {
375 SetTraceFilter(log_filter_);
376 initialized_ = false;
377 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
378 SetTraceOptions("");
379 if (tracing_->SetTraceCallback(this) == -1) {
380 LOG_RTCERR0(SetTraceCallback);
381 }
382 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
383 LOG_RTCERR0(RegisterVoiceEngineObserver);
384 }
385 // Clear the default agc state.
386 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
387
388 // Load our audio codec list.
389 ConstructCodecs();
390
391 // Load our RTP Header extensions.
392 rtp_header_extensions_.push_back(
393 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
394 kRtpAudioLevelHeaderExtensionId));
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000395 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000396
397 // Initialize the VoE Configuration to the default ACM.
398 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
399 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400}
401
402static bool IsOpus(const AudioCodec& codec) {
403 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
404}
405
406static bool IsIsac(const AudioCodec& codec) {
407 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
408}
409
410// True if params["stereo"] == "1"
411static bool IsOpusStereoEnabled(const AudioCodec& codec) {
412 CodecParameterMap::const_iterator param =
413 codec.params.find(kCodecParamStereo);
414 if (param == codec.params.end()) {
415 return false;
416 }
417 return param->second == kParamValueTrue;
418}
419
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000420static bool IsValidOpusBitrate(int bitrate) {
421 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
422}
423
424// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
425// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
426static int GetOpusBitrateFromParams(const AudioCodec& codec) {
427 int bitrate = 0;
428 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
429 return 0;
430 }
431 if (!IsValidOpusBitrate(bitrate)) {
432 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
433 << "invalid value: " << bitrate;
434 return 0;
435 }
436 return bitrate;
437}
438
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439void WebRtcVoiceEngine::ConstructCodecs() {
440 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
441 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
442 for (int i = 0; i < ncodecs; ++i) {
443 webrtc::CodecInst voe_codec;
444 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
445 // Skip uncompressed formats.
446 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
447 continue;
448 }
449
450 const CodecPref* pref = NULL;
451 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
452 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
453 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
454 kCodecPrefs[j].channels == voe_codec.channels) {
455 pref = &kCodecPrefs[j];
456 break;
457 }
458 }
459
460 if (pref) {
461 // Use the payload type that we've configured in our pref table;
462 // use the offset in our pref table to determine the sort order.
463 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
464 voe_codec.rate, voe_codec.channels,
465 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
466 LOG(LS_INFO) << ToString(codec);
467 if (IsIsac(codec)) {
468 // Indicate auto-bandwidth in signaling.
469 codec.bitrate = 0;
470 }
471 if (IsOpus(codec)) {
472 // Only add fmtp parameters that differ from the spec.
473 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
474 codec.params[kCodecParamMinPTime] =
475 talk_base::ToString(kPreferredMinPTime);
476 }
477 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
478 codec.params[kCodecParamMaxPTime] =
479 talk_base::ToString(kPreferredMaxPTime);
480 }
481 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
482 // when they can be set to values other than the default.
483 }
484 codecs_.push_back(codec);
485 } else {
486 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
487 }
488 }
489 }
490 // Make sure they are in local preference order.
491 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
492}
493
494WebRtcVoiceEngine::~WebRtcVoiceEngine() {
495 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
496 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
497 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
498 }
499 if (adm_) {
500 voe_wrapper_.reset();
501 adm_->Release();
502 adm_ = NULL;
503 }
504 if (adm_sc_) {
505 voe_wrapper_sc_.reset();
506 adm_sc_->Release();
507 adm_sc_ = NULL;
508 }
509
510 // Test to see if the media processor was deregistered properly
511 ASSERT(SignalRxMediaFrame.is_empty());
512 ASSERT(SignalTxMediaFrame.is_empty());
513
514 tracing_->SetTraceCallback(NULL);
515}
516
517bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
518 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
519 bool res = InitInternal();
520 if (res) {
521 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
522 } else {
523 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
524 Terminate();
525 }
526 return res;
527}
528
529bool WebRtcVoiceEngine::InitInternal() {
530 // Temporarily turn logging level up for the Init call
531 int old_filter = log_filter_;
532 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
533 SetTraceFilter(extended_filter);
534 SetTraceOptions("");
535
536 // Init WebRtc VoiceEngine.
537 if (voe_wrapper_->base()->Init(adm_) == -1) {
538 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
539 SetTraceFilter(old_filter);
540 return false;
541 }
542
543 SetTraceFilter(old_filter);
544 SetTraceOptions(log_options_);
545
546 // Log the VoiceEngine version info
547 char buffer[1024] = "";
548 voe_wrapper_->base()->GetVersion(buffer);
549 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
550 LogMultiline(talk_base::LS_INFO, buffer);
551
552 // Save the default AGC configuration settings. This must happen before
553 // calling SetOptions or the default will be overwritten.
554 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000555 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000556 return false;
557 }
558
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000559 // Set defaults for options, so that ApplyOptions applies them explicitly
560 // when we clear option (channel) overrides. External clients can still
561 // modify the defaults via SetOptions (on the media engine).
562 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 return false;
564 }
565
566 // Print our codec list again for the call diagnostic log
567 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
568 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
569 it != codecs_.end(); ++it) {
570 LOG(LS_INFO) << ToString(*it);
571 }
572
wu@webrtc.org4551b792013-10-09 15:37:36 +0000573 // Disable the DTMF playout when a tone is sent.
574 // PlayDtmfTone will be used if local playout is needed.
575 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
576 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
577 }
578
579 initialized_ = true;
580 return true;
581}
582
583bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
584 if (voe_wrapper_sc_initialized_) {
585 return true;
586 }
587 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
588 // be false, so subsequent calls to EnsureSoundclipEngineInit will
589 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590#if defined(LINUX) && !defined(HAVE_LIBPULSE)
591 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
592#endif
593
594 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
595 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
596 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
597 return false;
598 }
599
600 // On Windows, tell it to use the default sound (not communication) devices.
601 // First check whether there is a valid sound device for playback.
602 // TODO(juberti): Clean this up when we support setting the soundclip device.
603#ifdef WIN32
604 // The SetPlayoutDevice may not be implemented in the case of external ADM.
605 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
606 // PeerConnection interface never set the adm_sc_, so need to check both
607 // in order to determine if the external adm is used.
608 if (!adm_ && !adm_sc_) {
609 int num_of_devices = 0;
610 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
611 num_of_devices > 0) {
612 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
613 == -1) {
614 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
615 voe_wrapper_sc_->error());
616 return false;
617 }
618 } else {
619 LOG(LS_WARNING) << "No valid sound playout device found.";
620 }
621 }
622#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000623 voe_wrapper_sc_initialized_ = true;
624 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625 return true;
626}
627
628void WebRtcVoiceEngine::Terminate() {
629 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
630 initialized_ = false;
631
632 StopAecDump();
633
wu@webrtc.org4551b792013-10-09 15:37:36 +0000634 if (voe_wrapper_sc_) {
635 voe_wrapper_sc_initialized_ = false;
636 voe_wrapper_sc_->base()->Terminate();
637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638 voe_wrapper_->base()->Terminate();
639 desired_local_monitor_enable_ = false;
640}
641
642int WebRtcVoiceEngine::GetCapabilities() {
643 return AUDIO_SEND | AUDIO_RECV;
644}
645
646VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
647 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
648 if (!ch->valid()) {
649 delete ch;
650 ch = NULL;
651 }
652 return ch;
653}
654
655SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000656 if (!EnsureSoundclipEngineInit()) {
657 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
658 << "initialize.";
659 return NULL;
660 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
662 if (!soundclip->Init() || !soundclip->Enable()) {
663 delete soundclip;
664 return NULL;
665 }
666 return soundclip;
667}
668
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000669bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000670 if (!ApplyOptions(options)) {
671 return false;
672 }
673 options_ = options;
674 return true;
675}
676
677bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
678 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
679 if (!ApplyOptions(overrides)) {
680 return false;
681 }
682 option_overrides_ = overrides;
683 return true;
684}
685
686bool WebRtcVoiceEngine::ClearOptionOverrides() {
687 LOG(LS_INFO) << "Clearing option overrides.";
688 AudioOptions options = options_;
689 // Only call ApplyOptions if |options_overrides_| contains overrided options.
690 // ApplyOptions affects NS, AGC other options that is shared between
691 // all WebRtcVoiceEngineChannels.
692 if (option_overrides_ == AudioOptions()) {
693 return true;
694 }
695
696 if (!ApplyOptions(options)) {
697 return false;
698 }
699 option_overrides_ = AudioOptions();
700 return true;
701}
702
703// AudioOptions defaults are set in InitInternal (for options with corresponding
704// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
705bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
706 AudioOptions options = options_in; // The options are modified below.
707 // kEcConference is AEC with high suppression.
708 webrtc::EcModes ec_mode = webrtc::kEcConference;
709 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
710 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
711 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
712 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000713 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
714 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
715 << aecm_comfort_noise << " (default is false).";
716 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717
718#if defined(IOS)
719 // On iOS, VPIO provides built-in EC and AGC.
720 options.echo_cancellation.Set(false);
721 options.auto_gain_control.Set(false);
722#elif defined(ANDROID)
723 ec_mode = webrtc::kEcAecm;
724#endif
725
726#if defined(IOS) || defined(ANDROID)
727 // Set the AGC mode for iOS as well despite disabling it above, to avoid
728 // unsupported configuration errors from webrtc.
729 agc_mode = webrtc::kAgcFixedDigital;
730 options.typing_detection.Set(false);
731 options.experimental_agc.Set(false);
732 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000733 options.experimental_ns.Set(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734#endif
735
736 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
737
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000738 // Configure whether ACM1 or ACM2 is used.
739 bool enable_acm2 = false;
740 if (options.experimental_acm.Get(&enable_acm2)) {
741 EnableExperimentalAcm(enable_acm2);
742 }
743
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
745
746 bool echo_cancellation;
747 if (options.echo_cancellation.Get(&echo_cancellation)) {
748 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
749 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
750 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000751 } else {
752 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
753 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754 }
755#if !defined(ANDROID)
756 // TODO(ajm): Remove the error return on Android from webrtc.
757 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
758 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
759 return false;
760 }
761#endif
762 if (ec_mode == webrtc::kEcAecm) {
763 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
764 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
765 return false;
766 }
767 }
768 }
769
770 bool auto_gain_control;
771 if (options.auto_gain_control.Get(&auto_gain_control)) {
772 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
773 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
774 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000775 } else {
776 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
777 << " with mode " << agc_mode;
778 }
779 }
780
781 if (options.tx_agc_target_dbov.IsSet() ||
782 options.tx_agc_digital_compression_gain.IsSet() ||
783 options.tx_agc_limiter.IsSet()) {
784 // Override default_agc_config_. Generally, an unset option means "leave
785 // the VoE bits alone" in this function, so we want whatever is set to be
786 // stored as the new "default". If we didn't, then setting e.g.
787 // tx_agc_target_dbov would reset digital compression gain and limiter
788 // settings.
789 // Also, if we don't update default_agc_config_, then adjust_agc_delta
790 // would be an offset from the original values, and not whatever was set
791 // explicitly.
792 default_agc_config_.targetLeveldBOv =
793 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
794 default_agc_config_.targetLeveldBOv);
795 default_agc_config_.digitalCompressionGaindB =
796 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
797 default_agc_config_.digitalCompressionGaindB);
798 default_agc_config_.limiterEnable =
799 options.tx_agc_limiter.GetWithDefaultIfUnset(
800 default_agc_config_.limiterEnable);
801 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
802 LOG_RTCERR3(SetAgcConfig,
803 default_agc_config_.targetLeveldBOv,
804 default_agc_config_.digitalCompressionGaindB,
805 default_agc_config_.limiterEnable);
806 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 }
808 }
809
810 bool noise_suppression;
811 if (options.noise_suppression.Get(&noise_suppression)) {
812 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
813 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
814 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000815 } else {
816 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
817 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 }
819 }
820
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000821#ifdef USE_WEBRTC_DEV_BRANCH
822 bool experimental_ns;
823 if (options.experimental_ns.Get(&experimental_ns)) {
824 webrtc::AudioProcessing* audioproc =
825 voe_wrapper_->base()->audio_processing();
826 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
827 // returns NULL on audio_processing().
828 if (audioproc) {
829 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
830 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
831 return false;
832 }
833 } else {
834 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
835 << experimental_ns;
836 }
837 }
838#endif // USE_WEBRTC_DEV_BRANCH
839
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 bool highpass_filter;
841 if (options.highpass_filter.Get(&highpass_filter)) {
842 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
843 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
844 return false;
845 }
846 }
847
848 bool stereo_swapping;
849 if (options.stereo_swapping.Get(&stereo_swapping)) {
850 voep->EnableStereoChannelSwapping(stereo_swapping);
851 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
852 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
853 return false;
854 }
855 }
856
857 bool typing_detection;
858 if (options.typing_detection.Get(&typing_detection)) {
859 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
860 // In case of error, log the info and continue
861 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
862 }
863 }
864
865 int adjust_agc_delta;
866 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
867 if (!AdjustAgcLevel(adjust_agc_delta)) {
868 return false;
869 }
870 }
871
872 bool aec_dump;
873 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000875 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 else
877 StopAecDump();
878 }
879
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000880 bool experimental_aec;
881 if (options.experimental_aec.Get(&experimental_aec)) {
882 webrtc::AudioProcessing* audioproc =
883 voe_wrapper_->base()->audio_processing();
884 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
885 // returns NULL on audio_processing().
886 if (audioproc) {
887 webrtc::Config config;
888 config.Set<webrtc::DelayCorrection>(
889 new webrtc::DelayCorrection(experimental_aec));
890 audioproc->SetExtraOptions(config);
891 }
892 }
893
wu@webrtc.org97077a32013-10-25 21:18:33 +0000894 uint32 recording_sample_rate;
895 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
896 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
897 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
898 }
899 }
900
901 uint32 playout_sample_rate;
902 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
903 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
904 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
905 }
906 }
907
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908
909 return true;
910}
911
912bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
913 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
914 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
915 LOG_RTCERR1(SetDelayOffsetMs, offset);
916 return false;
917 }
918
919 return true;
920}
921
922struct ResumeEntry {
923 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
924 : channel(c),
925 playout(p),
926 send(s) {
927 }
928
929 WebRtcVoiceMediaChannel *channel;
930 bool playout;
931 SendFlags send;
932};
933
934// TODO(juberti): Refactor this so that the core logic can be used to set the
935// soundclip device. At that time, reinstate the soundclip pause/resume code.
936bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
937 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000938#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
940 kDefaultAudioDeviceId;
941 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
942 kDefaultAudioDeviceId;
943 // The device manager uses -1 as the default device, which was the case for
944 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
945#ifndef WIN32
946 if (-1 == in_id) {
947 in_id = kDefaultAudioDeviceId;
948 }
949 if (-1 == out_id) {
950 out_id = kDefaultAudioDeviceId;
951 }
952#endif
953
954 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
955 in_device->name : "Default device";
956 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
957 out_device->name : "Default device";
958 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
959 << ") and speaker to (id=" << out_id << ", name=" << out_name
960 << ")";
961
962 // If we're running the local monitor, we need to stop it first.
963 bool ret = true;
964 if (!PauseLocalMonitor()) {
965 LOG(LS_WARNING) << "Failed to pause local monitor";
966 ret = false;
967 }
968
969 // Must also pause all audio playback and capture.
970 for (ChannelList::const_iterator i = channels_.begin();
971 i != channels_.end(); ++i) {
972 WebRtcVoiceMediaChannel *channel = *i;
973 if (!channel->PausePlayout()) {
974 LOG(LS_WARNING) << "Failed to pause playout";
975 ret = false;
976 }
977 if (!channel->PauseSend()) {
978 LOG(LS_WARNING) << "Failed to pause send";
979 ret = false;
980 }
981 }
982
983 // Find the recording device id in VoiceEngine and set recording device.
984 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
985 ret = false;
986 }
987 if (ret) {
988 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000989 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990 ret = false;
991 }
992 }
993
994 // Find the playout device id in VoiceEngine and set playout device.
995 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
996 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
997 ret = false;
998 }
999 if (ret) {
1000 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001001 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 ret = false;
1003 }
1004 }
1005
1006 // Resume all audio playback and capture.
1007 for (ChannelList::const_iterator i = channels_.begin();
1008 i != channels_.end(); ++i) {
1009 WebRtcVoiceMediaChannel *channel = *i;
1010 if (!channel->ResumePlayout()) {
1011 LOG(LS_WARNING) << "Failed to resume playout";
1012 ret = false;
1013 }
1014 if (!channel->ResumeSend()) {
1015 LOG(LS_WARNING) << "Failed to resume send";
1016 ret = false;
1017 }
1018 }
1019
1020 // Resume local monitor.
1021 if (!ResumeLocalMonitor()) {
1022 LOG(LS_WARNING) << "Failed to resume local monitor";
1023 ret = false;
1024 }
1025
1026 if (ret) {
1027 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1028 << ") and speaker to (id="<< out_id << " name=" << out_name
1029 << ")";
1030 }
1031
1032 return ret;
1033#else
1034 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001035#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036}
1037
1038bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1039 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1040 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001041#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 *rtc_id = dev_id;
1043 return true;
1044#else
1045 // In Windows and Mac, we need to find the VoiceEngine device id by name
1046 // unless the input dev_id is the default device id.
1047 if (kDefaultAudioDeviceId == dev_id) {
1048 *rtc_id = dev_id;
1049 return true;
1050 }
1051
1052 // Get the number of VoiceEngine audio devices.
1053 int count = 0;
1054 if (is_input) {
1055 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1056 LOG_RTCERR0(GetNumOfRecordingDevices);
1057 return false;
1058 }
1059 } else {
1060 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1061 LOG_RTCERR0(GetNumOfPlayoutDevices);
1062 return false;
1063 }
1064 }
1065
1066 for (int i = 0; i < count; ++i) {
1067 char name[128];
1068 char guid[128];
1069 if (is_input) {
1070 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1071 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1072 } else {
1073 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1074 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1075 }
1076
1077 std::string webrtc_name(name);
1078 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1079 *rtc_id = i;
1080 return true;
1081 }
1082 }
1083 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1084 return false;
1085#endif
1086}
1087
1088bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1089 unsigned int ulevel;
1090 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1091 LOG_RTCERR1(GetSpeakerVolume, level);
1092 return false;
1093 }
1094 *level = ulevel;
1095 return true;
1096}
1097
1098bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1099 ASSERT(level >= 0 && level <= 255);
1100 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1101 LOG_RTCERR1(SetSpeakerVolume, level);
1102 return false;
1103 }
1104 return true;
1105}
1106
1107int WebRtcVoiceEngine::GetInputLevel() {
1108 unsigned int ulevel;
1109 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1110 static_cast<int>(ulevel) : -1;
1111}
1112
1113bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1114 desired_local_monitor_enable_ = enable;
1115 return ChangeLocalMonitor(desired_local_monitor_enable_);
1116}
1117
1118bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1119 // The voe file api is not available in chrome.
1120 if (!voe_wrapper_->file()) {
1121 return false;
1122 }
1123 if (enable && !monitor_) {
1124 monitor_.reset(new WebRtcMonitorStream);
1125 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1126 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1127 // Must call Stop() because there are some cases where Start will report
1128 // failure but still change the state, and if we leave VE in the on state
1129 // then it could crash later when trying to invoke methods on our monitor.
1130 voe_wrapper_->file()->StopRecordingMicrophone();
1131 monitor_.reset();
1132 return false;
1133 }
1134 } else if (!enable && monitor_) {
1135 voe_wrapper_->file()->StopRecordingMicrophone();
1136 monitor_.reset();
1137 }
1138 return true;
1139}
1140
1141bool WebRtcVoiceEngine::PauseLocalMonitor() {
1142 return ChangeLocalMonitor(false);
1143}
1144
1145bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1146 return ChangeLocalMonitor(desired_local_monitor_enable_);
1147}
1148
1149const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1150 return codecs_;
1151}
1152
1153bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1154 return FindWebRtcCodec(in, NULL);
1155}
1156
1157// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1158bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1159 webrtc::CodecInst* out) {
1160 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1161 for (int i = 0; i < ncodecs; ++i) {
1162 webrtc::CodecInst voe_codec;
1163 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1164 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1165 voe_codec.rate, voe_codec.channels, 0);
1166 bool multi_rate = IsCodecMultiRate(voe_codec);
1167 // Allow arbitrary rates for ISAC to be specified.
1168 if (multi_rate) {
1169 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1170 codec.bitrate = 0;
1171 }
1172 if (codec.Matches(in)) {
1173 if (out) {
1174 // Fixup the payload type.
1175 voe_codec.pltype = in.id;
1176
1177 // Set bitrate if specified.
1178 if (multi_rate && in.bitrate != 0) {
1179 voe_codec.rate = in.bitrate;
1180 }
1181
1182 // Apply codec-specific settings.
1183 if (IsIsac(codec)) {
1184 // If ISAC and an explicit bitrate is not specified,
1185 // enable auto bandwidth adjustment.
1186 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1187 }
1188 *out = voe_codec;
1189 }
1190 return true;
1191 }
1192 }
1193 }
1194 return false;
1195}
1196const std::vector<RtpHeaderExtension>&
1197WebRtcVoiceEngine::rtp_header_extensions() const {
1198 return rtp_header_extensions_;
1199}
1200
1201void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1202 // if min_sev == -1, we keep the current log level.
1203 if (min_sev >= 0) {
1204 SetTraceFilter(SeverityToFilter(min_sev));
1205 }
1206 log_options_ = filter;
1207 SetTraceOptions(initialized_ ? log_options_ : "");
1208}
1209
1210int WebRtcVoiceEngine::GetLastEngineError() {
1211 return voe_wrapper_->error();
1212}
1213
1214void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1215 log_filter_ = filter;
1216 tracing_->SetTraceFilter(filter);
1217}
1218
1219// We suppport three different logging settings for VoiceEngine:
1220// 1. Observer callback that goes into talk diagnostic logfile.
1221// Use --logfile and --loglevel
1222//
1223// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1224// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1225//
1226// 3. EC log and dump for debugging QualityEngine.
1227// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1228//
1229// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1230// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1231void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1232 // Set encrypted trace file.
1233 std::vector<std::string> opts;
1234 talk_base::tokenize(options, ' ', '"', '"', &opts);
1235 std::vector<std::string>::iterator tracefile =
1236 std::find(opts.begin(), opts.end(), "tracefile");
1237 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1238 // Write encrypted debug output (at same loglevel) to file
1239 // EncryptedTraceFile no longer supported.
1240 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1241 LOG_RTCERR1(SetTraceFile, *tracefile);
1242 }
1243 }
1244
wu@webrtc.org97077a32013-10-25 21:18:33 +00001245 // Allow trace options to override the trace filter. We default
1246 // it to log_filter_ (as a translation of libjingle log levels)
1247 // elsewhere, but this allows clients to explicitly set webrtc
1248 // log levels.
1249 std::vector<std::string>::iterator tracefilter =
1250 std::find(opts.begin(), opts.end(), "tracefilter");
1251 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1252 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1253 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1254 }
1255 }
1256
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257 // Set AEC dump file
1258 std::vector<std::string>::iterator recordEC =
1259 std::find(opts.begin(), opts.end(), "recordEC");
1260 if (recordEC != opts.end()) {
1261 ++recordEC;
1262 if (recordEC != opts.end())
1263 StartAecDump(recordEC->c_str());
1264 else
1265 StopAecDump();
1266 }
1267}
1268
1269// Ignore spammy trace messages, mostly from the stats API when we haven't
1270// gotten RTCP info yet from the remote side.
1271bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1272 static const char* kTracesToIgnore[] = {
1273 "\tfailed to GetReportBlockInformation",
1274 "GetRecCodec() failed to get received codec",
1275 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1276 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1277 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1278 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1279 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1280 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1281 "SenderInfoReceived No received SR",
1282 "StatisticsRTP() no statistics available",
1283 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1284 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1285 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1286 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1287 NULL
1288 };
1289 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1290 if (trace.find(*p) != std::string::npos) {
1291 return true;
1292 }
1293 }
1294 return false;
1295}
1296
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001297void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1298 if (enable == use_experimental_acm_)
1299 return;
1300 if (enable) {
1301 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1302 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1303 new webrtc::NewAudioCodingModuleFactory());
1304 } else {
1305 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1306 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1307 new webrtc::AudioCodingModuleFactory());
1308 }
1309 use_experimental_acm_ = enable;
1310}
1311
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1313 int length) {
1314 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1315 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1316 sev = talk_base::LS_ERROR;
1317 else if (level == webrtc::kTraceWarning)
1318 sev = talk_base::LS_WARNING;
1319 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1320 sev = talk_base::LS_INFO;
1321 else if (level == webrtc::kTraceTerseInfo)
1322 sev = talk_base::LS_INFO;
1323
1324 // Skip past boilerplate prefix text
1325 if (length < 72) {
1326 std::string msg(trace, length);
1327 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1328 LOG_V(sev) << msg;
1329 } else {
1330 std::string msg(trace + 71, length - 72);
1331 if (!ShouldIgnoreTrace(msg)) {
1332 LOG_V(sev) << "webrtc: " << msg;
1333 }
1334 }
1335}
1336
1337void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1338 talk_base::CritScope lock(&channels_cs_);
1339 WebRtcVoiceMediaChannel* channel = NULL;
1340 uint32 ssrc = 0;
1341 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1342 << channel_num << ".";
1343 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1344 ASSERT(channel != NULL);
1345 channel->OnError(ssrc, err_code);
1346 } else {
1347 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1348 << " could not be found in channel list when error reported.";
1349 }
1350}
1351
1352bool WebRtcVoiceEngine::FindChannelAndSsrc(
1353 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1354 ASSERT(channel != NULL && ssrc != NULL);
1355
1356 *channel = NULL;
1357 *ssrc = 0;
1358 // Find corresponding channel and ssrc
1359 for (ChannelList::const_iterator it = channels_.begin();
1360 it != channels_.end(); ++it) {
1361 ASSERT(*it != NULL);
1362 if ((*it)->FindSsrc(channel_num, ssrc)) {
1363 *channel = *it;
1364 return true;
1365 }
1366 }
1367
1368 return false;
1369}
1370
1371// This method will search through the WebRtcVoiceMediaChannels and
1372// obtain the voice engine's channel number.
1373bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1374 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1375 ASSERT(channel_num != NULL);
1376 ASSERT(direction == MPD_RX || direction == MPD_TX);
1377
1378 *channel_num = -1;
1379 // Find corresponding channel for ssrc.
1380 for (ChannelList::const_iterator it = channels_.begin();
1381 it != channels_.end(); ++it) {
1382 ASSERT(*it != NULL);
1383 if (direction & MPD_RX) {
1384 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1385 }
1386 if (*channel_num == -1 && (direction & MPD_TX)) {
1387 *channel_num = (*it)->GetSendChannelNum(ssrc);
1388 }
1389 if (*channel_num != -1) {
1390 return true;
1391 }
1392 }
1393 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1394 return false;
1395}
1396
1397void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1398 talk_base::CritScope lock(&channels_cs_);
1399 channels_.push_back(channel);
1400}
1401
1402void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1403 talk_base::CritScope lock(&channels_cs_);
1404 ChannelList::iterator i = std::find(channels_.begin(),
1405 channels_.end(),
1406 channel);
1407 if (i != channels_.end()) {
1408 channels_.erase(i);
1409 }
1410}
1411
1412void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1413 soundclips_.push_back(soundclip);
1414}
1415
1416void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1417 SoundclipList::iterator i = std::find(soundclips_.begin(),
1418 soundclips_.end(),
1419 soundclip);
1420 if (i != soundclips_.end()) {
1421 soundclips_.erase(i);
1422 }
1423}
1424
1425// Adjusts the default AGC target level by the specified delta.
1426// NB: If we start messing with other config fields, we'll want
1427// to save the current webrtc::AgcConfig as well.
1428bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1429 webrtc::AgcConfig config = default_agc_config_;
1430 config.targetLeveldBOv -= delta;
1431
1432 LOG(LS_INFO) << "Adjusting AGC level from default -"
1433 << default_agc_config_.targetLeveldBOv << "dB to -"
1434 << config.targetLeveldBOv << "dB";
1435
1436 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1437 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1438 return false;
1439 }
1440 return true;
1441}
1442
1443bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1444 webrtc::AudioDeviceModule* adm_sc) {
1445 if (initialized_) {
1446 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1447 return false;
1448 }
1449 if (adm_) {
1450 adm_->Release();
1451 adm_ = NULL;
1452 }
1453 if (adm) {
1454 adm_ = adm;
1455 adm_->AddRef();
1456 }
1457
1458 if (adm_sc_) {
1459 adm_sc_->Release();
1460 adm_sc_ = NULL;
1461 }
1462 if (adm_sc) {
1463 adm_sc_ = adm_sc;
1464 adm_sc_->AddRef();
1465 }
1466 return true;
1467}
1468
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001469bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1470 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1471 if (!aec_dump_file_stream) {
1472 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1473 if (!talk_base::ClosePlatformFile(file))
1474 LOG(LS_WARNING) << "Could not close file.";
1475 return false;
1476 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001477 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001478 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001479 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001480 LOG_RTCERR0(StartDebugRecording);
1481 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001482 return false;
1483 }
1484 is_dumping_aec_ = true;
1485 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001486}
1487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488bool WebRtcVoiceEngine::RegisterProcessor(
1489 uint32 ssrc,
1490 VoiceProcessor* voice_processor,
1491 MediaProcessorDirection direction) {
1492 bool register_with_webrtc = false;
1493 int channel_id = -1;
1494 bool success = false;
1495 uint32* processor_ssrc = NULL;
1496 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1497 if (voice_processor == NULL || !found_channel) {
1498 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1499 << " foundChannel: " << found_channel;
1500 return false;
1501 }
1502
1503 webrtc::ProcessingTypes processing_type;
1504 {
1505 talk_base::CritScope cs(&signal_media_critical_);
1506 if (direction == MPD_RX) {
1507 processing_type = webrtc::kPlaybackAllChannelsMixed;
1508 if (SignalRxMediaFrame.is_empty()) {
1509 register_with_webrtc = true;
1510 processor_ssrc = &rx_processor_ssrc_;
1511 }
1512 SignalRxMediaFrame.connect(voice_processor,
1513 &VoiceProcessor::OnFrame);
1514 } else {
1515 processing_type = webrtc::kRecordingPerChannel;
1516 if (SignalTxMediaFrame.is_empty()) {
1517 register_with_webrtc = true;
1518 processor_ssrc = &tx_processor_ssrc_;
1519 }
1520 SignalTxMediaFrame.connect(voice_processor,
1521 &VoiceProcessor::OnFrame);
1522 }
1523 }
1524 if (register_with_webrtc) {
1525 // TODO(janahan): when registering consider instantiating a
1526 // a VoeMediaProcess object and not make the engine extend the interface.
1527 if (voe()->media() && voe()->media()->
1528 RegisterExternalMediaProcessing(channel_id,
1529 processing_type,
1530 *this) != -1) {
1531 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1532 << channel_id;
1533 *processor_ssrc = ssrc;
1534 success = true;
1535 } else {
1536 LOG_RTCERR2(RegisterExternalMediaProcessing,
1537 channel_id,
1538 processing_type);
1539 success = false;
1540 }
1541 } else {
1542 // If we don't have to register with the engine, we just needed to
1543 // connect a new processor, set success to true;
1544 success = true;
1545 }
1546 return success;
1547}
1548
1549bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1550 MediaProcessorDirection channel_direction,
1551 uint32 ssrc,
1552 VoiceProcessor* voice_processor,
1553 MediaProcessorDirection processor_direction) {
1554 bool success = true;
1555 FrameSignal* signal;
1556 webrtc::ProcessingTypes processing_type;
1557 uint32* processor_ssrc = NULL;
1558 if (channel_direction == MPD_RX) {
1559 signal = &SignalRxMediaFrame;
1560 processing_type = webrtc::kPlaybackAllChannelsMixed;
1561 processor_ssrc = &rx_processor_ssrc_;
1562 } else {
1563 signal = &SignalTxMediaFrame;
1564 processing_type = webrtc::kRecordingPerChannel;
1565 processor_ssrc = &tx_processor_ssrc_;
1566 }
1567
1568 int deregister_id = -1;
1569 {
1570 talk_base::CritScope cs(&signal_media_critical_);
1571 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1572 signal->disconnect(voice_processor);
1573 int channel_id = -1;
1574 bool found_channel = FindChannelNumFromSsrc(ssrc,
1575 channel_direction,
1576 &channel_id);
1577 if (signal->is_empty() && found_channel) {
1578 deregister_id = channel_id;
1579 }
1580 }
1581 }
1582 if (deregister_id != -1) {
1583 if (voe()->media() &&
1584 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1585 processing_type) != -1) {
1586 *processor_ssrc = 0;
1587 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1588 << deregister_id;
1589 } else {
1590 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1591 deregister_id,
1592 processing_type);
1593 success = false;
1594 }
1595 }
1596 return success;
1597}
1598
1599bool WebRtcVoiceEngine::UnregisterProcessor(
1600 uint32 ssrc,
1601 VoiceProcessor* voice_processor,
1602 MediaProcessorDirection direction) {
1603 bool success = true;
1604 if (voice_processor == NULL) {
1605 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1606 << ssrc;
1607 return false;
1608 }
1609 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1610 success = false;
1611 }
1612 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1613 success = false;
1614 }
1615 return success;
1616}
1617
1618// Implementing method from WebRtc VoEMediaProcess interface
1619// Do not lock mux_channel_cs_ in this callback.
1620void WebRtcVoiceEngine::Process(int channel,
1621 webrtc::ProcessingTypes type,
1622 int16_t audio10ms[],
1623 int length,
1624 int sampling_freq,
1625 bool is_stereo) {
1626 talk_base::CritScope cs(&signal_media_critical_);
1627 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1628 if (type == webrtc::kPlaybackAllChannelsMixed) {
1629 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1630 } else if (type == webrtc::kRecordingPerChannel) {
1631 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1632 } else {
1633 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1634 << " channel: " << channel << " type: " << type
1635 << " tx_ssrc: " << tx_processor_ssrc_
1636 << " rx_ssrc: " << rx_processor_ssrc_;
1637 }
1638}
1639
1640void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1641 if (!is_dumping_aec_) {
1642 // Start dumping AEC when we are not dumping.
1643 if (voe_wrapper_->processing()->StartDebugRecording(
1644 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001645 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001646 } else {
1647 is_dumping_aec_ = true;
1648 }
1649 }
1650}
1651
1652void WebRtcVoiceEngine::StopAecDump() {
1653 if (is_dumping_aec_) {
1654 // Stop dumping AEC when we are dumping.
1655 if (voe_wrapper_->processing()->StopDebugRecording() !=
1656 webrtc::AudioProcessing::kNoError) {
1657 LOG_RTCERR0(StopDebugRecording);
1658 }
1659 is_dumping_aec_ = false;
1660 }
1661}
1662
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001663int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001664 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001665}
1666
1667int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1668 return CreateVoiceChannel(voe_wrapper_.get());
1669}
1670
1671int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1672 return CreateVoiceChannel(voe_wrapper_sc_.get());
1673}
1674
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001675class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1676 : public AudioRenderer::Sink {
1677 public:
1678 WebRtcVoiceChannelRenderer(int ch,
1679 webrtc::AudioTransport* voe_audio_transport)
1680 : channel_(ch),
1681 voe_audio_transport_(voe_audio_transport),
1682 renderer_(NULL) {
1683 }
1684 virtual ~WebRtcVoiceChannelRenderer() {
1685 Stop();
1686 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001687
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001688 // Starts the rendering by setting a sink to the renderer to get data
1689 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001690 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001691 // TODO(xians): Make sure Start() is called only once.
1692 void Start(AudioRenderer* renderer) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001693 talk_base::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001694 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001695 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001696 ASSERT(renderer_ == renderer);
1697 return;
1698 }
1699
1700 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1701 // in getUserMedia by default.
1702 renderer->AddChannel(channel_);
1703 renderer->SetSink(this);
1704 renderer_ = renderer;
1705 }
1706
1707 // Stops rendering by setting the sink of the renderer to NULL. No data
1708 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001709 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001710 void Stop() {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001711 talk_base::CritScope lock(&lock_);
1712 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001713 return;
1714
1715 renderer_->RemoveChannel(channel_);
1716 renderer_->SetSink(NULL);
1717 renderer_ = NULL;
1718 }
1719
1720 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001721 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001722 virtual void OnData(const void* audio_data,
1723 int bits_per_sample,
1724 int sample_rate,
1725 int number_of_channels,
1726 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001727#ifdef USE_WEBRTC_DEV_BRANCH
1728 voe_audio_transport_->OnData(channel_,
1729 audio_data,
1730 bits_per_sample,
1731 sample_rate,
1732 number_of_channels,
1733 number_of_frames);
1734#endif
1735 }
1736
1737 // Callback from the |renderer_| when it is going away. In case Start() has
1738 // never been called, this callback won't be triggered.
1739 virtual void OnClose() OVERRIDE {
1740 talk_base::CritScope lock(&lock_);
1741 // Set |renderer_| to NULL to make sure no more callback will get into
1742 // the renderer.
1743 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001744 }
1745
1746 // Accessor to the VoE channel ID.
1747 int channel() const { return channel_; }
1748
1749 private:
1750 const int channel_;
1751 webrtc::AudioTransport* const voe_audio_transport_;
1752
1753 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1754 // PeerConnection will make sure invalidating the pointer before the object
1755 // goes away.
1756 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001757
1758 // Protects |renderer_| in Start(), Stop() and OnClose().
1759 talk_base::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001760};
1761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762// WebRtcVoiceMediaChannel
1763WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1764 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1765 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001766 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001767 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001768 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 options_(),
1770 dtmf_allowed_(false),
1771 desired_playout_(false),
1772 nack_enabled_(false),
1773 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001774 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775 desired_send_(SEND_NOTHING),
1776 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777 default_receive_ssrc_(0) {
1778 engine->RegisterChannel(this);
1779 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1780 << voe_channel();
1781
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001782 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783}
1784
1785WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1786 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1787 << voe_channel();
1788
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001789 // Remove any remaining send streams, the default channel will be deleted
1790 // later.
1791 while (!send_channels_.empty())
1792 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793
1794 // Unregister ourselves from the engine.
1795 engine()->UnregisterChannel(this);
1796 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001797 while (!receive_channels_.empty()) {
1798 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799 }
1800
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001801 // Delete the default channel.
1802 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803}
1804
1805bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1806 LOG(LS_INFO) << "Setting voice channel options: "
1807 << options.ToString();
1808
wu@webrtc.orgde305012013-10-31 15:40:38 +00001809 // Check if DSCP value is changed from previous.
1810 bool dscp_option_changed = (options_.dscp != options.dscp);
1811
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001812 // TODO(xians): Add support to set different options for different send
1813 // streams after we support multiple APMs.
1814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815 // We retain all of the existing options, and apply the given ones
1816 // on top. This means there is no way to "clear" options such that
1817 // they go back to the engine default.
1818 options_.SetAll(options);
1819
1820 if (send_ != SEND_NOTHING) {
1821 if (!engine()->SetOptionOverrides(options_)) {
1822 LOG(LS_WARNING) <<
1823 "Failed to engine SetOptionOverrides during channel SetOptions.";
1824 return false;
1825 }
1826 } else {
1827 // Will be interpreted when appropriate.
1828 }
1829
wu@webrtc.org97077a32013-10-25 21:18:33 +00001830 // Receiver-side auto gain control happens per channel, so set it here from
1831 // options. Note that, like conference mode, setting it on the engine won't
1832 // have the desired effect, since voice channels don't inherit options from
1833 // the media engine when those options are applied per-channel.
1834 bool rx_auto_gain_control;
1835 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1836 if (engine()->voe()->processing()->SetRxAgcStatus(
1837 voe_channel(), rx_auto_gain_control,
1838 webrtc::kAgcFixedDigital) == -1) {
1839 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1840 return false;
1841 } else {
1842 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1843 << " with mode " << webrtc::kAgcFixedDigital;
1844 }
1845 }
1846 if (options.rx_agc_target_dbov.IsSet() ||
1847 options.rx_agc_digital_compression_gain.IsSet() ||
1848 options.rx_agc_limiter.IsSet()) {
1849 webrtc::AgcConfig config;
1850 // If only some of the options are being overridden, get the current
1851 // settings for the channel and bail if they aren't available.
1852 if (!options.rx_agc_target_dbov.IsSet() ||
1853 !options.rx_agc_digital_compression_gain.IsSet() ||
1854 !options.rx_agc_limiter.IsSet()) {
1855 if (engine()->voe()->processing()->GetRxAgcConfig(
1856 voe_channel(), config) != 0) {
1857 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1858 << "channel " << voe_channel() << ". Since not all rx "
1859 << "agc options are specified, unable to safely set rx "
1860 << "agc options.";
1861 return false;
1862 }
1863 }
1864 config.targetLeveldBOv =
1865 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1866 config.targetLeveldBOv);
1867 config.digitalCompressionGaindB =
1868 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1869 config.digitalCompressionGaindB);
1870 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1871 config.limiterEnable);
1872 if (engine()->voe()->processing()->SetRxAgcConfig(
1873 voe_channel(), config) == -1) {
1874 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1875 config.digitalCompressionGaindB, config.limiterEnable);
1876 return false;
1877 }
1878 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001879 if (dscp_option_changed) {
1880 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001881 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001882 dscp = kAudioDscpValue;
1883 if (MediaChannel::SetDscp(dscp) != 0) {
1884 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1885 }
1886 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001887
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 LOG(LS_INFO) << "Set voice channel options. Current options: "
1889 << options_.ToString();
1890 return true;
1891}
1892
1893bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1894 const std::vector<AudioCodec>& codecs) {
1895 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 LOG(LS_INFO) << "Setting receive voice codecs:";
1897
1898 std::vector<AudioCodec> new_codecs;
1899 // Find all new codecs. We allow adding new codecs but don't allow changing
1900 // the payload type of codecs that is already configured since we might
1901 // already be receiving packets with that payload type.
1902 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001903 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 AudioCodec old_codec;
1905 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1906 if (old_codec.id != it->id) {
1907 LOG(LS_ERROR) << it->name << " payload type changed.";
1908 return false;
1909 }
1910 } else {
1911 new_codecs.push_back(*it);
1912 }
1913 }
1914 if (new_codecs.empty()) {
1915 // There are no new codecs to configure. Already configured codecs are
1916 // never removed.
1917 return true;
1918 }
1919
1920 if (playout_) {
1921 // Receive codecs can not be changed while playing. So we temporarily
1922 // pause playout.
1923 PausePlayout();
1924 }
1925
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001926 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1928 it != new_codecs.end() && ret; ++it) {
1929 webrtc::CodecInst voe_codec;
1930 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1931 LOG(LS_INFO) << ToString(*it);
1932 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001933 if (default_receive_ssrc_ == 0) {
1934 // Set the receive codecs on the default channel explicitly if the
1935 // default channel is not used by |receive_channels_|, this happens in
1936 // conference mode or in non-conference mode when there is no playout
1937 // channel.
1938 // TODO(xians): Figure out how we use the default channel in conference
1939 // mode.
1940 if (engine()->voe()->codec()->SetRecPayloadType(
1941 voe_channel(), voe_codec) == -1) {
1942 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1943 ret = false;
1944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 }
1946
1947 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001948 for (ChannelMap::iterator it = receive_channels_.begin();
1949 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001951 it->second->channel(), voe_codec) == -1) {
1952 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001953 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 ret = false;
1955 }
1956 }
1957 } else {
1958 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1959 ret = false;
1960 }
1961 }
1962 if (ret) {
1963 recv_codecs_ = codecs;
1964 }
1965
1966 if (desired_playout_ && !playout_) {
1967 ResumePlayout();
1968 }
1969 return ret;
1970}
1971
1972bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001973 int channel, const std::vector<AudioCodec>& codecs) {
1974 // Disable VAD, and FEC unless we know the other side wants them.
1975 engine()->voe()->codec()->SetVADStatus(channel, false);
1976 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1977 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978
1979 // Scan through the list to figure out the codec to use for sending, along
1980 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001981 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 webrtc::CodecInst send_codec;
1983 memset(&send_codec, 0, sizeof(send_codec));
1984
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001985 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1987 it != codecs.end(); ++it) {
1988 // Ignore codecs we don't know about. The negotiation step should prevent
1989 // this, but double-check to be sure.
1990 webrtc::CodecInst voe_codec;
1991 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001992 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 continue;
1994 }
1995
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001996 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
1997 // Skip telephone-event/CN codec, which will be handled later.
1998 continue;
1999 }
2000
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 // If OPUS, change what we send according to the "stereo" codec
2002 // parameter, and not the "channels" parameter. We set
2003 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2004 // the bitrate is not specified, i.e. is zero, we set it to the
2005 // appropriate default value for mono or stereo Opus.
2006 if (IsOpus(*it)) {
2007 if (IsOpusStereoEnabled(*it)) {
2008 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002009 if (!IsValidOpusBitrate(it->bitrate)) {
2010 if (it->bitrate != 0) {
2011 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2012 << it->bitrate
2013 << ") with default opus stereo bitrate: "
2014 << kOpusStereoBitrate;
2015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016 voe_codec.rate = kOpusStereoBitrate;
2017 }
2018 } else {
2019 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002020 if (!IsValidOpusBitrate(it->bitrate)) {
2021 if (it->bitrate != 0) {
2022 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2023 << it->bitrate
2024 << ") with default opus mono bitrate: "
2025 << kOpusMonoBitrate;
2026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 voe_codec.rate = kOpusMonoBitrate;
2028 }
2029 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002030 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2031 if (bitrate_from_params != 0) {
2032 voe_codec.rate = bitrate_from_params;
2033 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 }
2035
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002036 // We'll use the first codec in the list to actually send audio data.
2037 // Be sure to use the payload type requested by the remote side.
2038 // "red", for FEC audio, is a special case where the actual codec to be
2039 // used is specified in params.
2040 if (IsRedCodec(it->name)) {
2041 // Parse out the RED parameters. If we fail, just ignore RED;
2042 // we don't support all possible params/usage scenarios.
2043 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2044 continue;
2045 }
2046
2047 // Enable redundant encoding of the specified codec. Treat any
2048 // failure as a fatal internal error.
2049 LOG(LS_INFO) << "Enabling FEC";
2050 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2051 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2052 return false;
2053 }
2054 } else {
2055 send_codec = voe_codec;
2056 nack_enabled_ = IsNackEnabled(*it);
2057 SetNack(channel, nack_enabled_);
2058 }
2059 found_send_codec = true;
2060 break;
2061 }
2062
2063 if (!found_send_codec) {
2064 LOG(LS_WARNING) << "Received empty list of codecs.";
2065 return false;
2066 }
2067
2068 // Set the codec immediately, since SetVADStatus() depends on whether
2069 // the current codec is mono or stereo.
2070 if (!SetSendCodec(channel, send_codec))
2071 return false;
2072
2073 // Always update the |send_codec_| to the currently set send codec.
2074 send_codec_.reset(new webrtc::CodecInst(send_codec));
2075
2076 if (send_bw_setting_) {
2077 SetSendBandwidthInternal(send_bw_bps_);
2078 }
2079
2080 // Loop through the codecs list again to config the telephone-event/CN codec.
2081 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2082 it != codecs.end(); ++it) {
2083 // Ignore codecs we don't know about. The negotiation step should prevent
2084 // this, but double-check to be sure.
2085 webrtc::CodecInst voe_codec;
2086 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2087 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2088 continue;
2089 }
2090
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002091 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2092 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002093 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002094 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2095 channel, it->id) == -1) {
2096 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2097 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002098 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002099 } else if (IsCNCodec(it->name)) {
2100 // Turn voice activity detection/comfort noise on if supported.
2101 // Set the wideband CN payload type appropriately.
2102 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103 webrtc::PayloadFrequencies cn_freq;
2104 switch (it->clockrate) {
2105 case 8000:
2106 cn_freq = webrtc::kFreq8000Hz;
2107 break;
2108 case 16000:
2109 cn_freq = webrtc::kFreq16000Hz;
2110 break;
2111 case 32000:
2112 cn_freq = webrtc::kFreq32000Hz;
2113 break;
2114 default:
2115 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2116 << " not supported.";
2117 continue;
2118 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002119 // Set the CN payloadtype and the VAD status.
2120 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2121 if (cn_freq != webrtc::kFreq8000Hz) {
2122 if (engine()->voe()->codec()->SetSendCNPayloadType(
2123 channel, it->id, cn_freq) == -1) {
2124 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2125 // TODO(ajm): This failure condition will be removed from VoE.
2126 // Restore the return here when we update to a new enough webrtc.
2127 //
2128 // Not returning false because the SetSendCNPayloadType will fail if
2129 // the channel is already sending.
2130 // This can happen if the remote description is applied twice, for
2131 // example in the case of ROAP on top of JSEP, where both side will
2132 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002134 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002135 // Only turn on VAD if we have a CN payload type that matches the
2136 // clockrate for the codec we are going to use.
2137 if (it->clockrate == send_codec.plfreq) {
2138 LOG(LS_INFO) << "Enabling VAD";
2139 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2140 LOG_RTCERR2(SetVADStatus, channel, true);
2141 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 }
2143 }
2144 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002145 }
2146
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002147 return true;
2148}
2149
2150bool WebRtcVoiceMediaChannel::SetSendCodecs(
2151 const std::vector<AudioCodec>& codecs) {
2152 dtmf_allowed_ = false;
2153 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2154 it != codecs.end(); ++it) {
2155 // Find the DTMF telephone event "codec".
2156 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2157 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2158 dtmf_allowed_ = true;
2159 }
2160 }
2161
2162 // Cache the codecs in order to configure the channel created later.
2163 send_codecs_ = codecs;
2164 for (ChannelMap::iterator iter = send_channels_.begin();
2165 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002166 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002167 return false;
2168 }
2169 }
2170
2171 SetNack(receive_channels_, nack_enabled_);
2172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 return true;
2174}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002175
2176void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2177 bool nack_enabled) {
2178 for (ChannelMap::const_iterator it = channels.begin();
2179 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002180 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002181 }
2182}
2183
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002184void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002186 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2188 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002189 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002190 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2191 }
2192}
2193
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194bool WebRtcVoiceMediaChannel::SetSendCodec(
2195 const webrtc::CodecInst& send_codec) {
2196 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2197 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002198 for (ChannelMap::iterator iter = send_channels_.begin();
2199 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002200 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002201 return false;
2202 }
2203
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002204 return true;
2205}
2206
2207bool WebRtcVoiceMediaChannel::SetSendCodec(
2208 int channel, const webrtc::CodecInst& send_codec) {
2209 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2210 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2211
2212 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2213 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 return false;
2215 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216 return true;
2217}
2218
2219bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2220 const std::vector<RtpHeaderExtension>& extensions) {
2221 // We don't support any incoming extensions headers right now.
2222 return true;
2223}
2224
2225bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2226 const std::vector<RtpHeaderExtension>& extensions) {
2227 // Enable the audio level extension header if requested.
2228 std::vector<RtpHeaderExtension>::const_iterator it;
2229 for (it = extensions.begin(); it != extensions.end(); ++it) {
2230 if (it->uri == kRtpAudioLevelHeaderExtension) {
2231 break;
2232 }
2233 }
2234
2235 bool enable = (it != extensions.end());
2236 int id = 0;
2237
2238 if (enable) {
2239 id = it->id;
2240 if (id < kMinRtpHeaderExtensionId ||
2241 id > kMaxRtpHeaderExtensionId) {
2242 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2243 return false;
2244 }
2245 }
2246
2247 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002248 for (ChannelMap::const_iterator iter = send_channels_.begin();
2249 iter != send_channels_.end(); ++iter) {
2250 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002251 iter->second->channel(), enable, id) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002252 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002253 iter->second->channel(), enable, id);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002254 return false;
2255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 }
2257
2258 return true;
2259}
2260
2261bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2262 desired_playout_ = playout;
2263 return ChangePlayout(desired_playout_);
2264}
2265
2266bool WebRtcVoiceMediaChannel::PausePlayout() {
2267 return ChangePlayout(false);
2268}
2269
2270bool WebRtcVoiceMediaChannel::ResumePlayout() {
2271 return ChangePlayout(desired_playout_);
2272}
2273
2274bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2275 if (playout_ == playout) {
2276 return true;
2277 }
2278
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002279 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002281 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 // Only toggle the default channel if we don't have any other channels.
2283 result = SetPlayout(voe_channel(), playout);
2284 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002285 for (ChannelMap::iterator it = receive_channels_.begin();
2286 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002287 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002288 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002289 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002290 result = false;
2291 }
2292 }
2293
2294 if (result) {
2295 playout_ = playout;
2296 }
2297 return result;
2298}
2299
2300bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2301 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002302 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002303 return ChangeSend(desired_send_);
2304 return true;
2305}
2306
2307bool WebRtcVoiceMediaChannel::PauseSend() {
2308 return ChangeSend(SEND_NOTHING);
2309}
2310
2311bool WebRtcVoiceMediaChannel::ResumeSend() {
2312 return ChangeSend(desired_send_);
2313}
2314
2315bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2316 if (send_ == send) {
2317 return true;
2318 }
2319
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002320 // Change the settings on each send channel.
2321 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 engine()->SetOptionOverrides(options_);
2323
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324 // Change the settings on each send channel.
2325 for (ChannelMap::iterator iter = send_channels_.begin();
2326 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002327 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002330
2331 // Clear up the options after stopping sending.
2332 if (send == SEND_NOTHING)
2333 engine()->ClearOptionOverrides();
2334
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 send_ = send;
2336 return true;
2337}
2338
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002339bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2340 if (send == SEND_MICROPHONE) {
2341 if (engine()->voe()->base()->StartSend(channel) == -1) {
2342 LOG_RTCERR1(StartSend, channel);
2343 return false;
2344 }
2345 if (engine()->voe()->file() &&
2346 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2347 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2348 return false;
2349 }
2350 } else { // SEND_NOTHING
2351 ASSERT(send == SEND_NOTHING);
2352 if (engine()->voe()->base()->StopSend(channel) == -1) {
2353 LOG_RTCERR1(StopSend, channel);
2354 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002355 }
2356 }
2357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358 return true;
2359}
2360
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002361void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2362 if (engine()->voe()->network()->RegisterExternalTransport(
2363 channel, *this) == -1) {
2364 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2365 }
2366
2367 // Enable RTCP (for quality stats and feedback messages)
2368 EnableRtcp(channel);
2369
2370 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2371 ResetRecvCodecs(channel);
2372}
2373
2374bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2375 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2376 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2377 }
2378
2379 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2380 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381 return false;
2382 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002383
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002384 return true;
2385}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002386
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002387bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2388 // If the default channel is already used for sending create a new channel
2389 // otherwise use the default channel for sending.
2390 int channel = GetSendChannelNum(sp.first_ssrc());
2391 if (channel != -1) {
2392 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2393 return false;
2394 }
2395
2396 bool default_channel_is_available = true;
2397 for (ChannelMap::const_iterator iter = send_channels_.begin();
2398 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002399 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002400 default_channel_is_available = false;
2401 break;
2402 }
2403 }
2404 if (default_channel_is_available) {
2405 channel = voe_channel();
2406 } else {
2407 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002408 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002409 if (channel == -1) {
2410 LOG_RTCERR0(CreateChannel);
2411 return false;
2412 }
2413
2414 ConfigureSendChannel(channel);
2415 }
2416
2417 // Save the channel to send_channels_, so that RemoveSendStream() can still
2418 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002419#ifdef USE_WEBRTC_DEV_BRANCH
2420 webrtc::AudioTransport* audio_transport =
2421 engine()->voe()->base()->audio_transport();
2422#else
2423 webrtc::AudioTransport* audio_transport = NULL;
2424#endif
2425 send_channels_.insert(std::make_pair(
2426 sp.first_ssrc(),
2427 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002428
2429 // Set the send (local) SSRC.
2430 // If there are multiple send SSRCs, we can only set the first one here, and
2431 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2432 // (with a codec requires multiple SSRC(s)).
2433 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2434 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2435 return false;
2436 }
2437
2438 // At this point the channel's local SSRC has been updated. If the channel is
2439 // the default channel make sure that all the receive channels are updated as
2440 // well. Receive channels have to have the same SSRC as the default channel in
2441 // order to send receiver reports with this SSRC.
2442 if (IsDefaultChannel(channel)) {
2443 for (ChannelMap::const_iterator it = receive_channels_.begin();
2444 it != receive_channels_.end(); ++it) {
2445 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002446 if (!IsDefaultChannel(it->second->channel())) {
2447 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002448 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002449 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450 return false;
2451 }
2452 }
2453 }
2454 }
2455
2456 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2457 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2458 return false;
2459 }
2460
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002461 // Set the current codecs to be used for the new channel.
2462 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002463 return false;
2464
2465 return ChangeSend(channel, desired_send_);
2466}
2467
2468bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2469 ChannelMap::iterator it = send_channels_.find(ssrc);
2470 if (it == send_channels_.end()) {
2471 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2472 << " which doesn't exist.";
2473 return false;
2474 }
2475
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002476 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 ChangeSend(channel, SEND_NOTHING);
2478
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002479 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2480 // this will disconnect the audio renderer with the send channel.
2481 delete it->second;
2482 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002483
2484 if (IsDefaultChannel(channel)) {
2485 // Do not delete the default channel since the receive channels depend on
2486 // the default channel, recycle it instead.
2487 ChangeSend(channel, SEND_NOTHING);
2488 } else {
2489 // Clean up and delete the send channel.
2490 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2491 << " with VoiceEngine channel #" << channel << ".";
2492 if (!DeleteChannel(channel))
2493 return false;
2494 }
2495
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002496 if (send_channels_.empty())
2497 ChangeSend(SEND_NOTHING);
2498
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 return true;
2500}
2501
2502bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002503 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002504
2505 if (!VERIFY(sp.ssrcs.size() == 1))
2506 return false;
2507 uint32 ssrc = sp.first_ssrc();
2508
wu@webrtc.org78187522013-10-07 23:32:02 +00002509 if (ssrc == 0) {
2510 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2511 return false;
2512 }
2513
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002514 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2515 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 return false;
2517 }
2518
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002519 // Reuse default channel for recv stream in non-conference mode call
2520 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002521#ifdef USE_WEBRTC_DEV_BRANCH
2522 webrtc::AudioTransport* audio_transport =
2523 engine()->voe()->base()->audio_transport();
2524#else
2525 webrtc::AudioTransport* audio_transport = NULL;
2526#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002527 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2528 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2529 << " reuse default channel";
2530 default_receive_ssrc_ = sp.first_ssrc();
2531 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002532 default_receive_ssrc_,
2533 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002534 return SetPlayout(voe_channel(), playout_);
2535 }
2536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002538 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002539 if (channel == -1) {
2540 LOG_RTCERR0(CreateChannel);
2541 return false;
2542 }
2543
wu@webrtc.org78187522013-10-07 23:32:02 +00002544 if (!ConfigureRecvChannel(channel)) {
2545 DeleteChannel(channel);
2546 return false;
2547 }
2548
2549 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002550 std::make_pair(
2551 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002552
2553 LOG(LS_INFO) << "New audio stream " << ssrc
2554 << " registered to VoiceEngine channel #"
2555 << channel << ".";
2556 return true;
2557}
2558
2559bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560 // Configure to use external transport, like our default channel.
2561 if (engine()->voe()->network()->RegisterExternalTransport(
2562 channel, *this) == -1) {
2563 LOG_RTCERR2(SetExternalTransport, channel, this);
2564 return false;
2565 }
2566
2567 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002568 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2570 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002571 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002572 return false;
2573 }
2574 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002575 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 return false;
2577 }
2578
2579 // Use the same recv payload types as our default channel.
2580 ResetRecvCodecs(channel);
2581 if (!recv_codecs_.empty()) {
2582 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2583 it != recv_codecs_.end(); ++it) {
2584 webrtc::CodecInst voe_codec;
2585 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2586 voe_codec.pltype = it->id;
2587 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2588 if (engine()->voe()->codec()->GetRecPayloadType(
2589 voe_channel(), voe_codec) != -1) {
2590 if (engine()->voe()->codec()->SetRecPayloadType(
2591 channel, voe_codec) == -1) {
2592 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2593 return false;
2594 }
2595 }
2596 }
2597 }
2598 }
2599
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002600 if (InConferenceMode()) {
2601 // To be in par with the video, voe_channel() is not used for receiving in
2602 // a conference call.
2603 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2604 // This is the first stream in a multi user meeting. We can now
2605 // disable playback of the default stream. This since the default
2606 // stream will probably have received some initial packets before
2607 // the new stream was added. This will mean that the CN state from
2608 // the default channel will be mixed in with the other streams
2609 // throughout the whole meeting, which might be disturbing.
2610 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2611 SetPlayout(voe_channel(), false);
2612 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002614 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616 return SetPlayout(channel, playout_);
2617}
2618
2619bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002620 talk_base::CritScope lock(&receive_channels_cs_);
2621 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002622 if (it == receive_channels_.end()) {
2623 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2624 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002625 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002628 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2629 // will disconnect the audio renderer with the receive channel.
2630 // Cache the channel before the deletion.
2631 const int channel = it->second->channel();
2632 delete it->second;
2633 receive_channels_.erase(it);
2634
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002635 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002636 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002637 // Recycle the default channel is for recv stream.
2638 if (playout_)
2639 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002640
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002641 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002642 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002644
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002645 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002646 << " with VoiceEngine channel #" << channel << ".";
2647 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002648 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002649
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002650 bool enable_default_channel_playout = false;
2651 if (receive_channels_.empty()) {
2652 // The last stream was removed. We can now enable the default
2653 // channel for new channels to be played out immediately without
2654 // waiting for AddStream messages.
2655 // We do this for both conference mode and non-conference mode.
2656 // TODO(oja): Does the default channel still have it's CN state?
2657 enable_default_channel_playout = true;
2658 }
2659 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2660 default_receive_ssrc_ != 0) {
2661 // Only the default channel is active, enable the playout on default
2662 // channel.
2663 enable_default_channel_playout = true;
2664 }
2665 if (enable_default_channel_playout && playout_) {
2666 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2667 SetPlayout(voe_channel(), true);
2668 }
2669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670 return true;
2671}
2672
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002673bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2674 AudioRenderer* renderer) {
2675 ChannelMap::iterator it = receive_channels_.find(ssrc);
2676 if (it == receive_channels_.end()) {
2677 if (renderer) {
2678 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002679 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002680 return false;
2681 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002682
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683 // The channel likely has gone away, do nothing.
2684 return true;
2685 }
2686
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002687 if (renderer)
2688 it->second->Start(renderer);
2689 else
2690 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692 return true;
2693}
2694
2695bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2696 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002697 ChannelMap::iterator it = send_channels_.find(ssrc);
2698 if (it == send_channels_.end()) {
2699 if (renderer) {
2700 // Return an error if trying to set a valid renderer with an invalid ssrc.
2701 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2702 return false;
2703 }
2704
2705 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002706 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002707 }
2708
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002709 if (renderer)
2710 it->second->Start(renderer);
2711 else
2712 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002713
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714 return true;
2715}
2716
2717bool WebRtcVoiceMediaChannel::GetActiveStreams(
2718 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719 // In conference mode, the default channel should not be in
2720 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002721 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 for (ChannelMap::iterator it = receive_channels_.begin();
2723 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002724 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002725 if (level > 0) {
2726 actives->push_back(std::make_pair(it->first, level));
2727 }
2728 }
2729 return true;
2730}
2731
2732int WebRtcVoiceMediaChannel::GetOutputLevel() {
2733 // return the highest output level of all streams
2734 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002735 for (ChannelMap::iterator it = receive_channels_.begin();
2736 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002737 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002738 highest = talk_base::_max(level, highest);
2739 }
2740 return highest;
2741}
2742
2743int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2744 int ret;
2745 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2746 // In case of error, log the info and continue
2747 LOG_RTCERR0(TimeSinceLastTyping);
2748 ret = -1;
2749 } else {
2750 ret *= 1000; // We return ms, webrtc returns seconds.
2751 }
2752 return ret;
2753}
2754
2755void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2756 int cost_per_typing, int reporting_threshold, int penalty_decay,
2757 int type_event_delay) {
2758 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2759 time_window, cost_per_typing,
2760 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2761 // In case of error, log the info and continue
2762 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2763 cost_per_typing, reporting_threshold, penalty_decay,
2764 type_event_delay);
2765 }
2766}
2767
2768bool WebRtcVoiceMediaChannel::SetOutputScaling(
2769 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 // Collect the channels to scale the output volume.
2772 std::vector<int> channels;
2773 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774 // Default channel is not in receive_channels_ if it is not being used for
2775 // playout.
2776 if (default_receive_ssrc_ == 0)
2777 channels.push_back(voe_channel());
2778 for (ChannelMap::const_iterator it = receive_channels_.begin();
2779 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002780 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002781 }
2782 } else { // Collect only the channel of the specified ssrc.
2783 int channel = GetReceiveChannelNum(ssrc);
2784 if (-1 == channel) {
2785 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2786 return false;
2787 }
2788 channels.push_back(channel);
2789 }
2790
2791 // Scale the output volume for the collected channels. We first normalize to
2792 // scale the volume and then set the left and right pan.
2793 float scale = static_cast<float>(talk_base::_max(left, right));
2794 if (scale > 0.0001f) {
2795 left /= scale;
2796 right /= scale;
2797 }
2798 for (std::vector<int>::const_iterator it = channels.begin();
2799 it != channels.end(); ++it) {
2800 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2801 *it, scale)) {
2802 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2803 return false;
2804 }
2805 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2806 *it, static_cast<float>(left), static_cast<float>(right))) {
2807 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2808 // Do not return if fails. SetOutputVolumePan is not available for all
2809 // pltforms.
2810 }
2811 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2812 << " right=" << right * scale
2813 << " for channel " << *it << " and ssrc " << ssrc;
2814 }
2815 return true;
2816}
2817
2818bool WebRtcVoiceMediaChannel::GetOutputScaling(
2819 uint32 ssrc, double* left, double* right) {
2820 if (!left || !right) return false;
2821
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002823 // Determine which channel based on ssrc.
2824 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2825 if (channel == -1) {
2826 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2827 return false;
2828 }
2829
2830 float scaling;
2831 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2832 channel, scaling)) {
2833 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2834 return false;
2835 }
2836
2837 float left_pan;
2838 float right_pan;
2839 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2840 channel, left_pan, right_pan)) {
2841 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2842 // If GetOutputVolumePan fails, we use the default left and right pan.
2843 left_pan = 1.0f;
2844 right_pan = 1.0f;
2845 }
2846
2847 *left = scaling * left_pan;
2848 *right = scaling * right_pan;
2849 return true;
2850}
2851
2852bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2853 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2854 return true;
2855}
2856
2857bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2858 bool play, bool loop) {
2859 if (!ringback_tone_) {
2860 return false;
2861 }
2862
2863 // The voe file api is not available in chrome.
2864 if (!engine()->voe()->file()) {
2865 return false;
2866 }
2867
2868 // Determine which VoiceEngine channel to play on.
2869 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2870 if (channel == -1) {
2871 return false;
2872 }
2873
2874 // Make sure the ringtone is cued properly, and play it out.
2875 if (play) {
2876 ringback_tone_->set_loop(loop);
2877 ringback_tone_->Rewind();
2878 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2879 ringback_tone_.get()) == -1) {
2880 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2881 LOG(LS_ERROR) << "Unable to start ringback tone";
2882 return false;
2883 }
2884 ringback_channels_.insert(channel);
2885 LOG(LS_INFO) << "Started ringback on channel " << channel;
2886 } else {
2887 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2888 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2889 LOG_RTCERR1(StopPlayingFileLocally, channel);
2890 return false;
2891 }
2892 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2893 ringback_channels_.erase(channel);
2894 }
2895
2896 return true;
2897}
2898
2899bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2900 return dtmf_allowed_;
2901}
2902
2903bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2904 int duration, int flags) {
2905 if (!dtmf_allowed_) {
2906 return false;
2907 }
2908
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909 // Send the event.
2910 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002911 int channel = -1;
2912 if (ssrc == 0) {
2913 bool default_channel_is_inuse = false;
2914 for (ChannelMap::const_iterator iter = send_channels_.begin();
2915 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002916 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002917 default_channel_is_inuse = true;
2918 break;
2919 }
2920 }
2921 if (default_channel_is_inuse) {
2922 channel = voe_channel();
2923 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002924 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002925 }
2926 } else {
2927 channel = GetSendChannelNum(ssrc);
2928 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002929 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2931 << ssrc << " is not in use.";
2932 return false;
2933 }
2934 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002935 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2936 channel, event, true, duration) == -1) {
2937 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938 return false;
2939 }
2940 }
2941
2942 // Play the event.
2943 if (flags & cricket::DF_PLAY) {
2944 // Play DTMF tone locally.
2945 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2946 LOG_RTCERR2(PlayDtmfTone, event, duration);
2947 return false;
2948 }
2949 }
2950
2951 return true;
2952}
2953
wu@webrtc.orga9890802013-12-13 00:21:03 +00002954void WebRtcVoiceMediaChannel::OnPacketReceived(
2955 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 // Pick which channel to send this packet to. If this packet doesn't match
2957 // any multiplexed streams, just send it to the default channel. Otherwise,
2958 // send it to the specific decoder instance for that stream.
2959 int which_channel = GetReceiveChannelNum(
2960 ParseSsrc(packet->data(), packet->length(), false));
2961 if (which_channel == -1) {
2962 which_channel = voe_channel();
2963 }
2964
2965 // Stop any ringback that might be playing on the channel.
2966 // It's possible the ringback has already stopped, ih which case we'll just
2967 // use the opportunity to remove the channel from ringback_channels_.
2968 if (engine()->voe()->file()) {
2969 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2970 if (it != ringback_channels_.end()) {
2971 if (engine()->voe()->file()->IsPlayingFileLocally(
2972 which_channel) == 1) {
2973 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2974 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2975 << " due to incoming media";
2976 }
2977 ringback_channels_.erase(which_channel);
2978 }
2979 }
2980
2981 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002982 engine()->voe()->network()->ReceivedRTPPacket(
2983 which_channel,
2984 packet->data(),
2985 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002986}
2987
wu@webrtc.orga9890802013-12-13 00:21:03 +00002988void WebRtcVoiceMediaChannel::OnRtcpReceived(
2989 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002990 // Sending channels need all RTCP packets with feedback information.
2991 // Even sender reports can contain attached report blocks.
2992 // Receiving channels need sender reports in order to create
2993 // correct receiver reports.
2994 int type = 0;
2995 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2996 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2997 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 }
2999
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003000 // If it is a sender report, find the channel that is listening.
3001 bool has_sent_to_default_channel = false;
3002 if (type == kRtcpTypeSR) {
3003 int which_channel = GetReceiveChannelNum(
3004 ParseSsrc(packet->data(), packet->length(), true));
3005 if (which_channel != -1) {
3006 engine()->voe()->network()->ReceivedRTCPPacket(
3007 which_channel,
3008 packet->data(),
3009 static_cast<unsigned int>(packet->length()));
3010
3011 if (IsDefaultChannel(which_channel))
3012 has_sent_to_default_channel = true;
3013 }
3014 }
3015
3016 // SR may continue RR and any RR entry may correspond to any one of the send
3017 // channels. So all RTCP packets must be forwarded all send channels. VoE
3018 // will filter out RR internally.
3019 for (ChannelMap::iterator iter = send_channels_.begin();
3020 iter != send_channels_.end(); ++iter) {
3021 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003022 if (IsDefaultChannel(iter->second->channel()) &&
3023 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003024 continue;
3025
3026 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003027 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003028 packet->data(),
3029 static_cast<unsigned int>(packet->length()));
3030 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003031}
3032
3033bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003034 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3035 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003036 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3037 return false;
3038 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003039 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3040 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041 return false;
3042 }
3043 return true;
3044}
3045
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003046bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3047 // TODO(andresp): Add support for setting an independent start bandwidth when
3048 // bandwidth estimation is enabled for voice engine.
3049 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003050}
3051
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003052bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3053 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3054
3055 return SetSendBandwidthInternal(bps);
3056}
3057
3058bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3059 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3060
3061 send_bw_setting_ = true;
3062 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003063
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003065 LOG(LS_INFO) << "The send codec has not been set up yet. "
3066 << "The send bandwidth setting will be applied later.";
3067 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 }
3069
3070 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003071 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3072 // SetMaxSendBandwith(0), the second call removes the previous limit.
3073 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003074 return true;
3075
3076 webrtc::CodecInst codec = *send_codec_;
3077 bool is_multi_rate = IsCodecMultiRate(codec);
3078
3079 if (is_multi_rate) {
3080 // If codec is multi-rate then just set the bitrate.
3081 codec.rate = bps;
3082 if (!SetSendCodec(codec)) {
3083 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3084 << " to bitrate " << bps << " bps.";
3085 return false;
3086 }
3087 return true;
3088 } else {
3089 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3090 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3091 // fixed bitrate then ignore.
3092 if (bps < codec.rate) {
3093 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3094 << " to bitrate " << bps << " bps"
3095 << ", requires at least " << codec.rate << " bps.";
3096 return false;
3097 }
3098 return true;
3099 }
3100}
3101
3102bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003103 bool echo_metrics_on = false;
3104 // These can take on valid negative values, so use the lowest possible level
3105 // as default rather than -1.
3106 int echo_return_loss = -100;
3107 int echo_return_loss_enhancement = -100;
3108 // These can also be negative, but in practice -1 is only used to signal
3109 // insufficient data, since the resolution is limited to multiples of 4 ms.
3110 int echo_delay_median_ms = -1;
3111 int echo_delay_std_ms = -1;
3112 if (engine()->voe()->processing()->GetEcMetricsStatus(
3113 echo_metrics_on) != -1 && echo_metrics_on) {
3114 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3115 // here, but it appears to be unsuitable currently. Revisit after this is
3116 // investigated: http://b/issue?id=5666755
3117 int erl, erle, rerl, anlp;
3118 if (engine()->voe()->processing()->GetEchoMetrics(
3119 erl, erle, rerl, anlp) != -1) {
3120 echo_return_loss = erl;
3121 echo_return_loss_enhancement = erle;
3122 }
3123
3124 int median, std;
3125 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3126 echo_delay_median_ms = median;
3127 echo_delay_std_ms = std;
3128 }
3129 }
3130
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003131 webrtc::CallStatistics cs;
3132 unsigned int ssrc;
3133 webrtc::CodecInst codec;
3134 unsigned int level;
3135
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003136 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3137 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003138 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003140 // Fill in the sender info, based on what we know, and what the
3141 // remote side told us it got from its RTCP report.
3142 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003143
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003144 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3145 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3146 continue;
3147 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003149 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003150 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3151 sinfo.bytes_sent = cs.bytesSent;
3152 sinfo.packets_sent = cs.packetsSent;
3153 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3154 // returns 0 to indicate an error value.
3155 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3156
3157 // Get data from the last remote RTCP report. Use default values if no data
3158 // available.
3159 sinfo.fraction_lost = -1.0;
3160 sinfo.jitter_ms = -1;
3161 sinfo.packets_lost = -1;
3162 sinfo.ext_seqnum = -1;
3163 std::vector<webrtc::ReportBlock> receive_blocks;
3164 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3165 channel, &receive_blocks) != -1 &&
3166 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3167 std::vector<webrtc::ReportBlock>::iterator iter;
3168 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3169 ++iter) {
3170 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003171 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003172 // Convert Q8 to floating point.
3173 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3174 // Convert samples to milliseconds.
3175 if (codec.plfreq / 1000 > 0) {
3176 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3177 }
3178 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3179 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3180 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182 }
3183 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003184
3185 // Local speech level.
3186 sinfo.audio_level = (engine()->voe()->volume()->
3187 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3188
3189 // TODO(xians): We are injecting the same APM logging to all the send
3190 // channels here because there is no good way to know which send channel
3191 // is using the APM. The correct fix is to allow the send channels to have
3192 // their own APM so that we can feed the correct APM logging to different
3193 // send channels. See issue crbug/264611 .
3194 sinfo.echo_return_loss = echo_return_loss;
3195 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3196 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3197 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003198 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3199 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003200 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003201
3202 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203 }
3204
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003205 // Build the list of receivers, one for each receiving channel, or 1 in
3206 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003208 for (ChannelMap::const_iterator it = receive_channels_.begin();
3209 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003210 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 }
3212 if (channels.empty()) {
3213 channels.push_back(voe_channel());
3214 }
3215
3216 // Get the SSRC and stats for each receiver, based on our own calculations.
3217 for (std::vector<int>::const_iterator it = channels.begin();
3218 it != channels.end(); ++it) {
3219 memset(&cs, 0, sizeof(cs));
3220 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3221 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3222 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3223 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003224 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225 rinfo.bytes_rcvd = cs.bytesReceived;
3226 rinfo.packets_rcvd = cs.packetsReceived;
3227 // The next four fields are from the most recently sent RTCP report.
3228 // Convert Q8 to floating point.
3229 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3230 rinfo.packets_lost = cs.cumulativeLost;
3231 rinfo.ext_seqnum = cs.extendedMax;
3232 // Convert samples to milliseconds.
3233 if (codec.plfreq / 1000 > 0) {
3234 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3235 }
3236
3237 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3238 webrtc::NetworkStatistics ns;
3239 if (engine()->voe()->neteq() &&
3240 engine()->voe()->neteq()->GetNetworkStatistics(
3241 *it, ns) != -1) {
3242 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3243 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3244 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003245 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003247
3248 webrtc::AudioDecodingCallStats ds;
3249 if (engine()->voe()->neteq() &&
3250 engine()->voe()->neteq()->GetDecodingCallStatistics(
3251 *it, &ds) != -1) {
3252 rinfo.decoding_calls_to_silence_generator =
3253 ds.calls_to_silence_generator;
3254 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3255 rinfo.decoding_normal = ds.decoded_normal;
3256 rinfo.decoding_plc = ds.decoded_plc;
3257 rinfo.decoding_cng = ds.decoded_cng;
3258 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3259 }
3260
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003262 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 int playout_buffer_delay_ms = 0;
3264 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003265 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3266 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3267 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003268 }
3269
3270 // Get speech level.
3271 rinfo.audio_level = (engine()->voe()->volume()->
3272 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3273 info->receivers.push_back(rinfo);
3274 }
3275 }
3276
3277 return true;
3278}
3279
3280void WebRtcVoiceMediaChannel::GetLastMediaError(
3281 uint32* ssrc, VoiceMediaChannel::Error* error) {
3282 ASSERT(ssrc != NULL);
3283 ASSERT(error != NULL);
3284 FindSsrc(voe_channel(), ssrc);
3285 *error = WebRtcErrorToChannelError(GetLastEngineError());
3286}
3287
3288bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003289 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003291 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3293 // This means the error is not limited to a specific channel. Signal the
3294 // message using ssrc=0. If the current channel is sending, use this
3295 // channel for sending the message.
3296 *ssrc = 0;
3297 return true;
3298 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003299 // Check whether this is a sending channel.
3300 for (ChannelMap::const_iterator it = send_channels_.begin();
3301 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003302 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003303 // This is a sending channel.
3304 uint32 local_ssrc = 0;
3305 if (engine()->voe()->rtp()->GetLocalSSRC(
3306 channel_num, local_ssrc) != -1) {
3307 *ssrc = local_ssrc;
3308 }
3309 return true;
3310 }
3311 }
3312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003313 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003314 for (ChannelMap::const_iterator it = receive_channels_.begin();
3315 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003316 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 *ssrc = it->first;
3318 return true;
3319 }
3320 }
3321 }
3322 return false;
3323}
3324
3325void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003326 if (error == VE_TYPING_NOISE_WARNING) {
3327 typing_noise_detected_ = true;
3328 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3329 typing_noise_detected_ = false;
3330 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003331 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3332}
3333
3334int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3335 unsigned int ulevel;
3336 int ret =
3337 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3338 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3339}
3340
3341int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003342 ChannelMap::iterator it = receive_channels_.find(ssrc);
3343 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003344 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003345 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3346}
3347
3348int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003349 ChannelMap::iterator it = send_channels_.find(ssrc);
3350 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003351 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003352
3353 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354}
3355
3356bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3357 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3358 // Get the RED encodings from the parameter with no name. This may
3359 // change based on what is discussed on the Jingle list.
3360 // The encoding parameter is of the form "a/b"; we only support where
3361 // a == b. Verify this and parse out the value into red_pt.
3362 // If the parameter value is absent (as it will be until we wire up the
3363 // signaling of this message), use the second codec specified (i.e. the
3364 // one after "red") as the encoding parameter.
3365 int red_pt = -1;
3366 std::string red_params;
3367 CodecParameterMap::const_iterator it = red_codec.params.find("");
3368 if (it != red_codec.params.end()) {
3369 red_params = it->second;
3370 std::vector<std::string> red_pts;
3371 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3372 red_pts[0] != red_pts[1] ||
3373 !talk_base::FromString(red_pts[0], &red_pt)) {
3374 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3375 return false;
3376 }
3377 } else if (red_codec.params.empty()) {
3378 LOG(LS_WARNING) << "RED params not present, using defaults";
3379 if (all_codecs.size() > 1) {
3380 red_pt = all_codecs[1].id;
3381 }
3382 }
3383
3384 // Try to find red_pt in |codecs|.
3385 std::vector<AudioCodec>::const_iterator codec;
3386 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3387 if (codec->id == red_pt)
3388 break;
3389 }
3390
3391 // If we find the right codec, that will be the codec we pass to
3392 // SetSendCodec, with the desired payload type.
3393 if (codec != all_codecs.end() &&
3394 engine()->FindWebRtcCodec(*codec, send_codec)) {
3395 } else {
3396 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3397 return false;
3398 }
3399
3400 return true;
3401}
3402
3403bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3404 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003405 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 return false;
3407 }
3408 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3409 // what we want to do with them.
3410 // engine()->voe().EnableVQMon(voe_channel(), true);
3411 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3412 return true;
3413}
3414
3415bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3416 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3417 for (int i = 0; i < ncodecs; ++i) {
3418 webrtc::CodecInst voe_codec;
3419 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3420 voe_codec.pltype = -1;
3421 if (engine()->voe()->codec()->SetRecPayloadType(
3422 channel, voe_codec) == -1) {
3423 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3424 return false;
3425 }
3426 }
3427 }
3428 return true;
3429}
3430
3431bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3432 if (playout) {
3433 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3434 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3435 LOG_RTCERR1(StartPlayout, channel);
3436 return false;
3437 }
3438 } else {
3439 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3440 engine()->voe()->base()->StopPlayout(channel);
3441 }
3442 return true;
3443}
3444
3445uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3446 bool rtcp) {
3447 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3448 uint32 ssrc = 0;
3449 if (len >= (ssrc_pos + sizeof(ssrc))) {
3450 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3451 }
3452 return ssrc;
3453}
3454
3455// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3456VoiceMediaChannel::Error
3457 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3458 switch (err_code) {
3459 case 0:
3460 return ERROR_NONE;
3461 case VE_CANNOT_START_RECORDING:
3462 case VE_MIC_VOL_ERROR:
3463 case VE_GET_MIC_VOL_ERROR:
3464 case VE_CANNOT_ACCESS_MIC_VOL:
3465 return ERROR_REC_DEVICE_OPEN_FAILED;
3466 case VE_SATURATION_WARNING:
3467 return ERROR_REC_DEVICE_SATURATION;
3468 case VE_REC_DEVICE_REMOVED:
3469 return ERROR_REC_DEVICE_REMOVED;
3470 case VE_RUNTIME_REC_WARNING:
3471 case VE_RUNTIME_REC_ERROR:
3472 return ERROR_REC_RUNTIME_ERROR;
3473 case VE_CANNOT_START_PLAYOUT:
3474 case VE_SPEAKER_VOL_ERROR:
3475 case VE_GET_SPEAKER_VOL_ERROR:
3476 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3477 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3478 case VE_RUNTIME_PLAY_WARNING:
3479 case VE_RUNTIME_PLAY_ERROR:
3480 return ERROR_PLAY_RUNTIME_ERROR;
3481 case VE_TYPING_NOISE_WARNING:
3482 return ERROR_REC_TYPING_NOISE_DETECTED;
3483 default:
3484 return VoiceMediaChannel::ERROR_OTHER;
3485 }
3486}
3487
3488int WebRtcSoundclipStream::Read(void *buf, int len) {
3489 size_t res = 0;
3490 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003491 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492}
3493
3494int WebRtcSoundclipStream::Rewind() {
3495 mem_.Rewind();
3496 // Return -1 to keep VoiceEngine from looping.
3497 return (loop_) ? 0 : -1;
3498}
3499
3500} // namespace cricket
3501
3502#endif // HAVE_WEBRTC_VOICE