blob: 8db8c99a68065206803dea81b95b7438ad88408f [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
41#include "talk/base/base64.h"
42#include "talk/base/byteorder.h"
43#include "talk/base/common.h"
44#include "talk/base/helpers.h"
45#include "talk/base/logging.h"
46#include "talk/base/stringencode.h"
47#include "talk/base/stringutils.h"
48#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
110// extension header for audio levels, as defined in
111// http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03
112static const char kRtpAudioLevelHeaderExtension[] =
113 "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
114static const int kRtpAudioLevelHeaderExtensionId = 1;
115
116static const char kIsacCodecName[] = "ISAC";
117static const char kL16CodecName[] = "L16";
118// Codec parameters for Opus.
119static const int kOpusMonoBitrate = 32000;
120// Parameter used for NACK.
121// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
122static const int kNackMaxPackets = 250;
123static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000124// draft-spittka-payload-rtp-opus-03
125// Opus bitrate should be in the range between 6000 and 510000.
126static const int kOpusMinBitrate = 6000;
127static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000128// Default audio dscp value.
129// See http://tools.ietf.org/html/rfc2474 for details.
130// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
131static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000133// Ensure we open the file in a writeable path on ChromeOS and Android. This
134// workaround can be removed when it's possible to specify a filename for audio
135// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000136//
137// TODO(grunell): Use a string in the options instead of hardcoding it here
138// and let the embedder choose the filename (crbug.com/264223).
139//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
141// below.
142#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144#elif defined(ANDROID)
145static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000146#else
147static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
148#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Dumps an AudioCodec in RFC 2327-ish format.
151static std::string ToString(const AudioCodec& codec) {
152 std::stringstream ss;
153 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154 << " (" << codec.id << ")";
155 return ss.str();
156}
157static std::string ToString(const webrtc::CodecInst& codec) {
158 std::stringstream ss;
159 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160 << " (" << codec.pltype << ")";
161 return ss.str();
162}
163
164static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
165 const char* delim = "\r\n";
166 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
167 LOG_V(sev) << tok;
168 }
169}
170
171// Severity is an integer because it comes is assumed to be from command line.
172static int SeverityToFilter(int severity) {
173 int filter = webrtc::kTraceNone;
174 switch (severity) {
175 case talk_base::LS_VERBOSE:
176 filter |= webrtc::kTraceAll;
177 case talk_base::LS_INFO:
178 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
179 case talk_base::LS_WARNING:
180 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
181 case talk_base::LS_ERROR:
182 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
183 }
184 return filter;
185}
186
187static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190 kCodecPrefs[i].clockrate == codec.plfreq) {
191 return kCodecPrefs[i].is_multi_rate;
192 }
193 }
194 return false;
195}
196
197static bool FindCodec(const std::vector<AudioCodec>& codecs,
198 const AudioCodec& codec,
199 AudioCodec* found_codec) {
200 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
201 it != codecs.end(); ++it) {
202 if (it->Matches(codec)) {
203 if (found_codec != NULL) {
204 *found_codec = *it;
205 }
206 return true;
207 }
208 }
209 return false;
210}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000211
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212static bool IsNackEnabled(const AudioCodec& codec) {
213 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
214 kParamValueEmpty));
215}
216
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217// Gets the default set of options applied to the engine. Historically, these
218// were supplied as a combination of flags from the channel manager (ec, agc,
219// ns, and highpass) and the rest hardcoded in InitInternal.
220static AudioOptions GetDefaultEngineOptions() {
221 AudioOptions options;
222 options.echo_cancellation.Set(true);
223 options.auto_gain_control.Set(true);
224 options.noise_suppression.Set(true);
225 options.highpass_filter.Set(true);
226 options.stereo_swapping.Set(false);
227 options.typing_detection.Set(true);
228 options.conference_mode.Set(false);
229 options.adjust_agc_delta.Set(0);
230 options.experimental_agc.Set(false);
231 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000232 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000233 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000234 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000235 return options;
236}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000237
238class WebRtcSoundclipMedia : public SoundclipMedia {
239 public:
240 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
241 : engine_(engine), webrtc_channel_(-1) {
242 engine_->RegisterSoundclip(this);
243 }
244
245 virtual ~WebRtcSoundclipMedia() {
246 engine_->UnregisterSoundclip(this);
247 if (webrtc_channel_ != -1) {
248 // We shouldn't have to call Disable() here. DeleteChannel() should call
249 // StopPlayout() while deleting the channel. We should fix the bug
250 // inside WebRTC and remove the Disable() call bellow. This work is
251 // tracked by bug http://b/issue?id=5382855.
252 PlaySound(NULL, 0, 0);
253 Disable();
254 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
255 == -1) {
256 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
257 }
258 }
259 }
260
261 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000262 if (!engine_->voe_sc()) {
263 return false;
264 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000265 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266 if (webrtc_channel_ == -1) {
267 LOG_RTCERR0(CreateChannel);
268 return false;
269 }
270 return true;
271 }
272
273 bool Enable() {
274 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
275 LOG_RTCERR1(StartPlayout, webrtc_channel_);
276 return false;
277 }
278 return true;
279 }
280
281 bool Disable() {
282 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
283 LOG_RTCERR1(StopPlayout, webrtc_channel_);
284 return false;
285 }
286 return true;
287 }
288
289 virtual bool PlaySound(const char *buf, int len, int flags) {
290 // The voe file api is not available in chrome.
291 if (!engine_->voe_sc()->file()) {
292 return false;
293 }
294 // Must stop playing the current sound (if any), because we are about to
295 // modify the stream.
296 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
297 == -1) {
298 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
299 return false;
300 }
301
302 if (buf) {
303 stream_.reset(new WebRtcSoundclipStream(buf, len));
304 stream_->set_loop((flags & SF_LOOP) != 0);
305 stream_->Rewind();
306
307 // Play it.
308 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
309 webrtc_channel_, stream_.get()) == -1) {
310 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
311 LOG(LS_ERROR) << "Unable to start soundclip";
312 return false;
313 }
314 } else {
315 stream_.reset();
316 }
317 return true;
318 }
319
320 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
321
322 private:
323 WebRtcVoiceEngine *engine_;
324 int webrtc_channel_;
325 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
326};
327
328WebRtcVoiceEngine::WebRtcVoiceEngine()
329 : voe_wrapper_(new VoEWrapper()),
330 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000331 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332 tracing_(new VoETraceWrapper()),
333 adm_(NULL),
334 adm_sc_(NULL),
335 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
336 is_dumping_aec_(false),
337 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000338 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339 tx_processor_ssrc_(0),
340 rx_processor_ssrc_(0) {
341 Construct();
342}
343
344WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
345 VoEWrapper* voe_wrapper_sc,
346 VoETraceWrapper* tracing)
347 : voe_wrapper_(voe_wrapper),
348 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000349 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000350 tracing_(tracing),
351 adm_(NULL),
352 adm_sc_(NULL),
353 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
354 is_dumping_aec_(false),
355 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000356 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000357 tx_processor_ssrc_(0),
358 rx_processor_ssrc_(0) {
359 Construct();
360}
361
362void WebRtcVoiceEngine::Construct() {
363 SetTraceFilter(log_filter_);
364 initialized_ = false;
365 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
366 SetTraceOptions("");
367 if (tracing_->SetTraceCallback(this) == -1) {
368 LOG_RTCERR0(SetTraceCallback);
369 }
370 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
371 LOG_RTCERR0(RegisterVoiceEngineObserver);
372 }
373 // Clear the default agc state.
374 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
375
376 // Load our audio codec list.
377 ConstructCodecs();
378
379 // Load our RTP Header extensions.
380 rtp_header_extensions_.push_back(
381 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
382 kRtpAudioLevelHeaderExtensionId));
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000383 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000384
385 // Initialize the VoE Configuration to the default ACM.
386 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
387 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388}
389
390static bool IsOpus(const AudioCodec& codec) {
391 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
392}
393
394static bool IsIsac(const AudioCodec& codec) {
395 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
396}
397
398// True if params["stereo"] == "1"
399static bool IsOpusStereoEnabled(const AudioCodec& codec) {
400 CodecParameterMap::const_iterator param =
401 codec.params.find(kCodecParamStereo);
402 if (param == codec.params.end()) {
403 return false;
404 }
405 return param->second == kParamValueTrue;
406}
407
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000408static bool IsValidOpusBitrate(int bitrate) {
409 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
410}
411
412// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
413// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
414static int GetOpusBitrateFromParams(const AudioCodec& codec) {
415 int bitrate = 0;
416 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
417 return 0;
418 }
419 if (!IsValidOpusBitrate(bitrate)) {
420 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
421 << "invalid value: " << bitrate;
422 return 0;
423 }
424 return bitrate;
425}
426
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000427void WebRtcVoiceEngine::ConstructCodecs() {
428 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
429 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
430 for (int i = 0; i < ncodecs; ++i) {
431 webrtc::CodecInst voe_codec;
432 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
433 // Skip uncompressed formats.
434 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
435 continue;
436 }
437
438 const CodecPref* pref = NULL;
439 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
440 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
441 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
442 kCodecPrefs[j].channels == voe_codec.channels) {
443 pref = &kCodecPrefs[j];
444 break;
445 }
446 }
447
448 if (pref) {
449 // Use the payload type that we've configured in our pref table;
450 // use the offset in our pref table to determine the sort order.
451 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
452 voe_codec.rate, voe_codec.channels,
453 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
454 LOG(LS_INFO) << ToString(codec);
455 if (IsIsac(codec)) {
456 // Indicate auto-bandwidth in signaling.
457 codec.bitrate = 0;
458 }
459 if (IsOpus(codec)) {
460 // Only add fmtp parameters that differ from the spec.
461 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
462 codec.params[kCodecParamMinPTime] =
463 talk_base::ToString(kPreferredMinPTime);
464 }
465 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
466 codec.params[kCodecParamMaxPTime] =
467 talk_base::ToString(kPreferredMaxPTime);
468 }
469 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
470 // when they can be set to values other than the default.
471 }
472 codecs_.push_back(codec);
473 } else {
474 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
475 }
476 }
477 }
478 // Make sure they are in local preference order.
479 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
480}
481
482WebRtcVoiceEngine::~WebRtcVoiceEngine() {
483 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
484 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
485 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
486 }
487 if (adm_) {
488 voe_wrapper_.reset();
489 adm_->Release();
490 adm_ = NULL;
491 }
492 if (adm_sc_) {
493 voe_wrapper_sc_.reset();
494 adm_sc_->Release();
495 adm_sc_ = NULL;
496 }
497
498 // Test to see if the media processor was deregistered properly
499 ASSERT(SignalRxMediaFrame.is_empty());
500 ASSERT(SignalTxMediaFrame.is_empty());
501
502 tracing_->SetTraceCallback(NULL);
503}
504
505bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
506 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
507 bool res = InitInternal();
508 if (res) {
509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
510 } else {
511 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
512 Terminate();
513 }
514 return res;
515}
516
517bool WebRtcVoiceEngine::InitInternal() {
518 // Temporarily turn logging level up for the Init call
519 int old_filter = log_filter_;
520 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
521 SetTraceFilter(extended_filter);
522 SetTraceOptions("");
523
524 // Init WebRtc VoiceEngine.
525 if (voe_wrapper_->base()->Init(adm_) == -1) {
526 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
527 SetTraceFilter(old_filter);
528 return false;
529 }
530
531 SetTraceFilter(old_filter);
532 SetTraceOptions(log_options_);
533
534 // Log the VoiceEngine version info
535 char buffer[1024] = "";
536 voe_wrapper_->base()->GetVersion(buffer);
537 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
538 LogMultiline(talk_base::LS_INFO, buffer);
539
540 // Save the default AGC configuration settings. This must happen before
541 // calling SetOptions or the default will be overwritten.
542 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000543 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000544 return false;
545 }
546
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000547 // Set defaults for options, so that ApplyOptions applies them explicitly
548 // when we clear option (channel) overrides. External clients can still
549 // modify the defaults via SetOptions (on the media engine).
550 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551 return false;
552 }
553
554 // Print our codec list again for the call diagnostic log
555 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
556 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
557 it != codecs_.end(); ++it) {
558 LOG(LS_INFO) << ToString(*it);
559 }
560
wu@webrtc.org4551b792013-10-09 15:37:36 +0000561 // Disable the DTMF playout when a tone is sent.
562 // PlayDtmfTone will be used if local playout is needed.
563 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
564 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
565 }
566
567 initialized_ = true;
568 return true;
569}
570
571bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
572 if (voe_wrapper_sc_initialized_) {
573 return true;
574 }
575 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
576 // be false, so subsequent calls to EnsureSoundclipEngineInit will
577 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578#if defined(LINUX) && !defined(HAVE_LIBPULSE)
579 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
580#endif
581
582 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
583 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
584 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
585 return false;
586 }
587
588 // On Windows, tell it to use the default sound (not communication) devices.
589 // First check whether there is a valid sound device for playback.
590 // TODO(juberti): Clean this up when we support setting the soundclip device.
591#ifdef WIN32
592 // The SetPlayoutDevice may not be implemented in the case of external ADM.
593 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
594 // PeerConnection interface never set the adm_sc_, so need to check both
595 // in order to determine if the external adm is used.
596 if (!adm_ && !adm_sc_) {
597 int num_of_devices = 0;
598 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
599 num_of_devices > 0) {
600 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
601 == -1) {
602 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
603 voe_wrapper_sc_->error());
604 return false;
605 }
606 } else {
607 LOG(LS_WARNING) << "No valid sound playout device found.";
608 }
609 }
610#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000611 voe_wrapper_sc_initialized_ = true;
612 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 return true;
614}
615
616void WebRtcVoiceEngine::Terminate() {
617 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
618 initialized_ = false;
619
620 StopAecDump();
621
wu@webrtc.org4551b792013-10-09 15:37:36 +0000622 if (voe_wrapper_sc_) {
623 voe_wrapper_sc_initialized_ = false;
624 voe_wrapper_sc_->base()->Terminate();
625 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 voe_wrapper_->base()->Terminate();
627 desired_local_monitor_enable_ = false;
628}
629
630int WebRtcVoiceEngine::GetCapabilities() {
631 return AUDIO_SEND | AUDIO_RECV;
632}
633
634VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
635 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
636 if (!ch->valid()) {
637 delete ch;
638 ch = NULL;
639 }
640 return ch;
641}
642
643SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000644 if (!EnsureSoundclipEngineInit()) {
645 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
646 << "initialize.";
647 return NULL;
648 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
650 if (!soundclip->Init() || !soundclip->Enable()) {
651 delete soundclip;
652 return NULL;
653 }
654 return soundclip;
655}
656
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000657bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 if (!ApplyOptions(options)) {
659 return false;
660 }
661 options_ = options;
662 return true;
663}
664
665bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
666 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
667 if (!ApplyOptions(overrides)) {
668 return false;
669 }
670 option_overrides_ = overrides;
671 return true;
672}
673
674bool WebRtcVoiceEngine::ClearOptionOverrides() {
675 LOG(LS_INFO) << "Clearing option overrides.";
676 AudioOptions options = options_;
677 // Only call ApplyOptions if |options_overrides_| contains overrided options.
678 // ApplyOptions affects NS, AGC other options that is shared between
679 // all WebRtcVoiceEngineChannels.
680 if (option_overrides_ == AudioOptions()) {
681 return true;
682 }
683
684 if (!ApplyOptions(options)) {
685 return false;
686 }
687 option_overrides_ = AudioOptions();
688 return true;
689}
690
691// AudioOptions defaults are set in InitInternal (for options with corresponding
692// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
693bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
694 AudioOptions options = options_in; // The options are modified below.
695 // kEcConference is AEC with high suppression.
696 webrtc::EcModes ec_mode = webrtc::kEcConference;
697 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
698 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
699 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
700 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000701 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
702 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
703 << aecm_comfort_noise << " (default is false).";
704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705
706#if defined(IOS)
707 // On iOS, VPIO provides built-in EC and AGC.
708 options.echo_cancellation.Set(false);
709 options.auto_gain_control.Set(false);
710#elif defined(ANDROID)
711 ec_mode = webrtc::kEcAecm;
712#endif
713
714#if defined(IOS) || defined(ANDROID)
715 // Set the AGC mode for iOS as well despite disabling it above, to avoid
716 // unsupported configuration errors from webrtc.
717 agc_mode = webrtc::kAgcFixedDigital;
718 options.typing_detection.Set(false);
719 options.experimental_agc.Set(false);
720 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000721 options.experimental_ns.Set(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722#endif
723
724 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
725
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000726 // Configure whether ACM1 or ACM2 is used.
727 bool enable_acm2 = false;
728 if (options.experimental_acm.Get(&enable_acm2)) {
729 EnableExperimentalAcm(enable_acm2);
730 }
731
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
733
734 bool echo_cancellation;
735 if (options.echo_cancellation.Get(&echo_cancellation)) {
736 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
737 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
738 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000739 } else {
740 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
741 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 }
743#if !defined(ANDROID)
744 // TODO(ajm): Remove the error return on Android from webrtc.
745 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
746 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
747 return false;
748 }
749#endif
750 if (ec_mode == webrtc::kEcAecm) {
751 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
752 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
753 return false;
754 }
755 }
756 }
757
758 bool auto_gain_control;
759 if (options.auto_gain_control.Get(&auto_gain_control)) {
760 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
761 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
762 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000763 } else {
764 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
765 << " with mode " << agc_mode;
766 }
767 }
768
769 if (options.tx_agc_target_dbov.IsSet() ||
770 options.tx_agc_digital_compression_gain.IsSet() ||
771 options.tx_agc_limiter.IsSet()) {
772 // Override default_agc_config_. Generally, an unset option means "leave
773 // the VoE bits alone" in this function, so we want whatever is set to be
774 // stored as the new "default". If we didn't, then setting e.g.
775 // tx_agc_target_dbov would reset digital compression gain and limiter
776 // settings.
777 // Also, if we don't update default_agc_config_, then adjust_agc_delta
778 // would be an offset from the original values, and not whatever was set
779 // explicitly.
780 default_agc_config_.targetLeveldBOv =
781 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
782 default_agc_config_.targetLeveldBOv);
783 default_agc_config_.digitalCompressionGaindB =
784 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
785 default_agc_config_.digitalCompressionGaindB);
786 default_agc_config_.limiterEnable =
787 options.tx_agc_limiter.GetWithDefaultIfUnset(
788 default_agc_config_.limiterEnable);
789 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
790 LOG_RTCERR3(SetAgcConfig,
791 default_agc_config_.targetLeveldBOv,
792 default_agc_config_.digitalCompressionGaindB,
793 default_agc_config_.limiterEnable);
794 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 }
796 }
797
798 bool noise_suppression;
799 if (options.noise_suppression.Get(&noise_suppression)) {
800 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
801 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
802 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000803 } else {
804 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
805 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 }
807 }
808
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000809#ifdef USE_WEBRTC_DEV_BRANCH
810 bool experimental_ns;
811 if (options.experimental_ns.Get(&experimental_ns)) {
812 webrtc::AudioProcessing* audioproc =
813 voe_wrapper_->base()->audio_processing();
814 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
815 // returns NULL on audio_processing().
816 if (audioproc) {
817 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
818 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
819 return false;
820 }
821 } else {
822 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
823 << experimental_ns;
824 }
825 }
826#endif // USE_WEBRTC_DEV_BRANCH
827
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 bool highpass_filter;
829 if (options.highpass_filter.Get(&highpass_filter)) {
830 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
831 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
832 return false;
833 }
834 }
835
836 bool stereo_swapping;
837 if (options.stereo_swapping.Get(&stereo_swapping)) {
838 voep->EnableStereoChannelSwapping(stereo_swapping);
839 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
840 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
841 return false;
842 }
843 }
844
845 bool typing_detection;
846 if (options.typing_detection.Get(&typing_detection)) {
847 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
848 // In case of error, log the info and continue
849 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
850 }
851 }
852
853 int adjust_agc_delta;
854 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
855 if (!AdjustAgcLevel(adjust_agc_delta)) {
856 return false;
857 }
858 }
859
860 bool aec_dump;
861 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000863 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 else
865 StopAecDump();
866 }
867
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000868 bool experimental_aec;
869 if (options.experimental_aec.Get(&experimental_aec)) {
870 webrtc::AudioProcessing* audioproc =
871 voe_wrapper_->base()->audio_processing();
872 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
873 // returns NULL on audio_processing().
874 if (audioproc) {
875 webrtc::Config config;
876 config.Set<webrtc::DelayCorrection>(
877 new webrtc::DelayCorrection(experimental_aec));
878 audioproc->SetExtraOptions(config);
879 }
880 }
881
wu@webrtc.org97077a32013-10-25 21:18:33 +0000882 uint32 recording_sample_rate;
883 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
884 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
885 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
886 }
887 }
888
889 uint32 playout_sample_rate;
890 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
891 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
892 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
893 }
894 }
895
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896
897 return true;
898}
899
900bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
901 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
902 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
903 LOG_RTCERR1(SetDelayOffsetMs, offset);
904 return false;
905 }
906
907 return true;
908}
909
910struct ResumeEntry {
911 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
912 : channel(c),
913 playout(p),
914 send(s) {
915 }
916
917 WebRtcVoiceMediaChannel *channel;
918 bool playout;
919 SendFlags send;
920};
921
922// TODO(juberti): Refactor this so that the core logic can be used to set the
923// soundclip device. At that time, reinstate the soundclip pause/resume code.
924bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
925 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000926#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
928 kDefaultAudioDeviceId;
929 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
930 kDefaultAudioDeviceId;
931 // The device manager uses -1 as the default device, which was the case for
932 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
933#ifndef WIN32
934 if (-1 == in_id) {
935 in_id = kDefaultAudioDeviceId;
936 }
937 if (-1 == out_id) {
938 out_id = kDefaultAudioDeviceId;
939 }
940#endif
941
942 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
943 in_device->name : "Default device";
944 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
945 out_device->name : "Default device";
946 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
947 << ") and speaker to (id=" << out_id << ", name=" << out_name
948 << ")";
949
950 // If we're running the local monitor, we need to stop it first.
951 bool ret = true;
952 if (!PauseLocalMonitor()) {
953 LOG(LS_WARNING) << "Failed to pause local monitor";
954 ret = false;
955 }
956
957 // Must also pause all audio playback and capture.
958 for (ChannelList::const_iterator i = channels_.begin();
959 i != channels_.end(); ++i) {
960 WebRtcVoiceMediaChannel *channel = *i;
961 if (!channel->PausePlayout()) {
962 LOG(LS_WARNING) << "Failed to pause playout";
963 ret = false;
964 }
965 if (!channel->PauseSend()) {
966 LOG(LS_WARNING) << "Failed to pause send";
967 ret = false;
968 }
969 }
970
971 // Find the recording device id in VoiceEngine and set recording device.
972 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
973 ret = false;
974 }
975 if (ret) {
976 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000977 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 ret = false;
979 }
980 }
981
982 // Find the playout device id in VoiceEngine and set playout device.
983 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
984 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
985 ret = false;
986 }
987 if (ret) {
988 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000989 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990 ret = false;
991 }
992 }
993
994 // Resume all audio playback and capture.
995 for (ChannelList::const_iterator i = channels_.begin();
996 i != channels_.end(); ++i) {
997 WebRtcVoiceMediaChannel *channel = *i;
998 if (!channel->ResumePlayout()) {
999 LOG(LS_WARNING) << "Failed to resume playout";
1000 ret = false;
1001 }
1002 if (!channel->ResumeSend()) {
1003 LOG(LS_WARNING) << "Failed to resume send";
1004 ret = false;
1005 }
1006 }
1007
1008 // Resume local monitor.
1009 if (!ResumeLocalMonitor()) {
1010 LOG(LS_WARNING) << "Failed to resume local monitor";
1011 ret = false;
1012 }
1013
1014 if (ret) {
1015 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1016 << ") and speaker to (id="<< out_id << " name=" << out_name
1017 << ")";
1018 }
1019
1020 return ret;
1021#else
1022 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001023#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024}
1025
1026bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1027 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1028 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001029#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 *rtc_id = dev_id;
1031 return true;
1032#else
1033 // In Windows and Mac, we need to find the VoiceEngine device id by name
1034 // unless the input dev_id is the default device id.
1035 if (kDefaultAudioDeviceId == dev_id) {
1036 *rtc_id = dev_id;
1037 return true;
1038 }
1039
1040 // Get the number of VoiceEngine audio devices.
1041 int count = 0;
1042 if (is_input) {
1043 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1044 LOG_RTCERR0(GetNumOfRecordingDevices);
1045 return false;
1046 }
1047 } else {
1048 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1049 LOG_RTCERR0(GetNumOfPlayoutDevices);
1050 return false;
1051 }
1052 }
1053
1054 for (int i = 0; i < count; ++i) {
1055 char name[128];
1056 char guid[128];
1057 if (is_input) {
1058 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1059 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1060 } else {
1061 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1062 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1063 }
1064
1065 std::string webrtc_name(name);
1066 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1067 *rtc_id = i;
1068 return true;
1069 }
1070 }
1071 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1072 return false;
1073#endif
1074}
1075
1076bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1077 unsigned int ulevel;
1078 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1079 LOG_RTCERR1(GetSpeakerVolume, level);
1080 return false;
1081 }
1082 *level = ulevel;
1083 return true;
1084}
1085
1086bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1087 ASSERT(level >= 0 && level <= 255);
1088 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1089 LOG_RTCERR1(SetSpeakerVolume, level);
1090 return false;
1091 }
1092 return true;
1093}
1094
1095int WebRtcVoiceEngine::GetInputLevel() {
1096 unsigned int ulevel;
1097 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1098 static_cast<int>(ulevel) : -1;
1099}
1100
1101bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1102 desired_local_monitor_enable_ = enable;
1103 return ChangeLocalMonitor(desired_local_monitor_enable_);
1104}
1105
1106bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1107 // The voe file api is not available in chrome.
1108 if (!voe_wrapper_->file()) {
1109 return false;
1110 }
1111 if (enable && !monitor_) {
1112 monitor_.reset(new WebRtcMonitorStream);
1113 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1114 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1115 // Must call Stop() because there are some cases where Start will report
1116 // failure but still change the state, and if we leave VE in the on state
1117 // then it could crash later when trying to invoke methods on our monitor.
1118 voe_wrapper_->file()->StopRecordingMicrophone();
1119 monitor_.reset();
1120 return false;
1121 }
1122 } else if (!enable && monitor_) {
1123 voe_wrapper_->file()->StopRecordingMicrophone();
1124 monitor_.reset();
1125 }
1126 return true;
1127}
1128
1129bool WebRtcVoiceEngine::PauseLocalMonitor() {
1130 return ChangeLocalMonitor(false);
1131}
1132
1133bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1134 return ChangeLocalMonitor(desired_local_monitor_enable_);
1135}
1136
1137const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1138 return codecs_;
1139}
1140
1141bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1142 return FindWebRtcCodec(in, NULL);
1143}
1144
1145// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1146bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1147 webrtc::CodecInst* out) {
1148 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1149 for (int i = 0; i < ncodecs; ++i) {
1150 webrtc::CodecInst voe_codec;
1151 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1152 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1153 voe_codec.rate, voe_codec.channels, 0);
1154 bool multi_rate = IsCodecMultiRate(voe_codec);
1155 // Allow arbitrary rates for ISAC to be specified.
1156 if (multi_rate) {
1157 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1158 codec.bitrate = 0;
1159 }
1160 if (codec.Matches(in)) {
1161 if (out) {
1162 // Fixup the payload type.
1163 voe_codec.pltype = in.id;
1164
1165 // Set bitrate if specified.
1166 if (multi_rate && in.bitrate != 0) {
1167 voe_codec.rate = in.bitrate;
1168 }
1169
1170 // Apply codec-specific settings.
1171 if (IsIsac(codec)) {
1172 // If ISAC and an explicit bitrate is not specified,
1173 // enable auto bandwidth adjustment.
1174 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1175 }
1176 *out = voe_codec;
1177 }
1178 return true;
1179 }
1180 }
1181 }
1182 return false;
1183}
1184const std::vector<RtpHeaderExtension>&
1185WebRtcVoiceEngine::rtp_header_extensions() const {
1186 return rtp_header_extensions_;
1187}
1188
1189void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1190 // if min_sev == -1, we keep the current log level.
1191 if (min_sev >= 0) {
1192 SetTraceFilter(SeverityToFilter(min_sev));
1193 }
1194 log_options_ = filter;
1195 SetTraceOptions(initialized_ ? log_options_ : "");
1196}
1197
1198int WebRtcVoiceEngine::GetLastEngineError() {
1199 return voe_wrapper_->error();
1200}
1201
1202void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1203 log_filter_ = filter;
1204 tracing_->SetTraceFilter(filter);
1205}
1206
1207// We suppport three different logging settings for VoiceEngine:
1208// 1. Observer callback that goes into talk diagnostic logfile.
1209// Use --logfile and --loglevel
1210//
1211// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1212// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1213//
1214// 3. EC log and dump for debugging QualityEngine.
1215// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1216//
1217// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1218// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1219void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1220 // Set encrypted trace file.
1221 std::vector<std::string> opts;
1222 talk_base::tokenize(options, ' ', '"', '"', &opts);
1223 std::vector<std::string>::iterator tracefile =
1224 std::find(opts.begin(), opts.end(), "tracefile");
1225 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1226 // Write encrypted debug output (at same loglevel) to file
1227 // EncryptedTraceFile no longer supported.
1228 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1229 LOG_RTCERR1(SetTraceFile, *tracefile);
1230 }
1231 }
1232
wu@webrtc.org97077a32013-10-25 21:18:33 +00001233 // Allow trace options to override the trace filter. We default
1234 // it to log_filter_ (as a translation of libjingle log levels)
1235 // elsewhere, but this allows clients to explicitly set webrtc
1236 // log levels.
1237 std::vector<std::string>::iterator tracefilter =
1238 std::find(opts.begin(), opts.end(), "tracefilter");
1239 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1240 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1241 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1242 }
1243 }
1244
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 // Set AEC dump file
1246 std::vector<std::string>::iterator recordEC =
1247 std::find(opts.begin(), opts.end(), "recordEC");
1248 if (recordEC != opts.end()) {
1249 ++recordEC;
1250 if (recordEC != opts.end())
1251 StartAecDump(recordEC->c_str());
1252 else
1253 StopAecDump();
1254 }
1255}
1256
1257// Ignore spammy trace messages, mostly from the stats API when we haven't
1258// gotten RTCP info yet from the remote side.
1259bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1260 static const char* kTracesToIgnore[] = {
1261 "\tfailed to GetReportBlockInformation",
1262 "GetRecCodec() failed to get received codec",
1263 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1264 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1265 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1266 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1267 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1268 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1269 "SenderInfoReceived No received SR",
1270 "StatisticsRTP() no statistics available",
1271 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1272 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1273 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1274 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1275 NULL
1276 };
1277 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1278 if (trace.find(*p) != std::string::npos) {
1279 return true;
1280 }
1281 }
1282 return false;
1283}
1284
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001285void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1286 if (enable == use_experimental_acm_)
1287 return;
1288 if (enable) {
1289 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1290 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1291 new webrtc::NewAudioCodingModuleFactory());
1292 } else {
1293 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1294 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1295 new webrtc::AudioCodingModuleFactory());
1296 }
1297 use_experimental_acm_ = enable;
1298}
1299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1301 int length) {
1302 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1303 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1304 sev = talk_base::LS_ERROR;
1305 else if (level == webrtc::kTraceWarning)
1306 sev = talk_base::LS_WARNING;
1307 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1308 sev = talk_base::LS_INFO;
1309 else if (level == webrtc::kTraceTerseInfo)
1310 sev = talk_base::LS_INFO;
1311
1312 // Skip past boilerplate prefix text
1313 if (length < 72) {
1314 std::string msg(trace, length);
1315 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1316 LOG_V(sev) << msg;
1317 } else {
1318 std::string msg(trace + 71, length - 72);
1319 if (!ShouldIgnoreTrace(msg)) {
1320 LOG_V(sev) << "webrtc: " << msg;
1321 }
1322 }
1323}
1324
1325void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1326 talk_base::CritScope lock(&channels_cs_);
1327 WebRtcVoiceMediaChannel* channel = NULL;
1328 uint32 ssrc = 0;
1329 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1330 << channel_num << ".";
1331 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1332 ASSERT(channel != NULL);
1333 channel->OnError(ssrc, err_code);
1334 } else {
1335 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1336 << " could not be found in channel list when error reported.";
1337 }
1338}
1339
1340bool WebRtcVoiceEngine::FindChannelAndSsrc(
1341 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1342 ASSERT(channel != NULL && ssrc != NULL);
1343
1344 *channel = NULL;
1345 *ssrc = 0;
1346 // Find corresponding channel and ssrc
1347 for (ChannelList::const_iterator it = channels_.begin();
1348 it != channels_.end(); ++it) {
1349 ASSERT(*it != NULL);
1350 if ((*it)->FindSsrc(channel_num, ssrc)) {
1351 *channel = *it;
1352 return true;
1353 }
1354 }
1355
1356 return false;
1357}
1358
1359// This method will search through the WebRtcVoiceMediaChannels and
1360// obtain the voice engine's channel number.
1361bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1362 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1363 ASSERT(channel_num != NULL);
1364 ASSERT(direction == MPD_RX || direction == MPD_TX);
1365
1366 *channel_num = -1;
1367 // Find corresponding channel for ssrc.
1368 for (ChannelList::const_iterator it = channels_.begin();
1369 it != channels_.end(); ++it) {
1370 ASSERT(*it != NULL);
1371 if (direction & MPD_RX) {
1372 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1373 }
1374 if (*channel_num == -1 && (direction & MPD_TX)) {
1375 *channel_num = (*it)->GetSendChannelNum(ssrc);
1376 }
1377 if (*channel_num != -1) {
1378 return true;
1379 }
1380 }
1381 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1382 return false;
1383}
1384
1385void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1386 talk_base::CritScope lock(&channels_cs_);
1387 channels_.push_back(channel);
1388}
1389
1390void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1391 talk_base::CritScope lock(&channels_cs_);
1392 ChannelList::iterator i = std::find(channels_.begin(),
1393 channels_.end(),
1394 channel);
1395 if (i != channels_.end()) {
1396 channels_.erase(i);
1397 }
1398}
1399
1400void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401 soundclips_.push_back(soundclip);
1402}
1403
1404void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1405 SoundclipList::iterator i = std::find(soundclips_.begin(),
1406 soundclips_.end(),
1407 soundclip);
1408 if (i != soundclips_.end()) {
1409 soundclips_.erase(i);
1410 }
1411}
1412
1413// Adjusts the default AGC target level by the specified delta.
1414// NB: If we start messing with other config fields, we'll want
1415// to save the current webrtc::AgcConfig as well.
1416bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1417 webrtc::AgcConfig config = default_agc_config_;
1418 config.targetLeveldBOv -= delta;
1419
1420 LOG(LS_INFO) << "Adjusting AGC level from default -"
1421 << default_agc_config_.targetLeveldBOv << "dB to -"
1422 << config.targetLeveldBOv << "dB";
1423
1424 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1425 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1426 return false;
1427 }
1428 return true;
1429}
1430
1431bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1432 webrtc::AudioDeviceModule* adm_sc) {
1433 if (initialized_) {
1434 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1435 return false;
1436 }
1437 if (adm_) {
1438 adm_->Release();
1439 adm_ = NULL;
1440 }
1441 if (adm) {
1442 adm_ = adm;
1443 adm_->AddRef();
1444 }
1445
1446 if (adm_sc_) {
1447 adm_sc_->Release();
1448 adm_sc_ = NULL;
1449 }
1450 if (adm_sc) {
1451 adm_sc_ = adm_sc;
1452 adm_sc_->AddRef();
1453 }
1454 return true;
1455}
1456
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001457bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1458 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1459 if (!aec_dump_file_stream) {
1460 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1461 if (!talk_base::ClosePlatformFile(file))
1462 LOG(LS_WARNING) << "Could not close file.";
1463 return false;
1464 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001465 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001466 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001467 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001468 LOG_RTCERR0(StartDebugRecording);
1469 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001470 return false;
1471 }
1472 is_dumping_aec_ = true;
1473 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476bool WebRtcVoiceEngine::RegisterProcessor(
1477 uint32 ssrc,
1478 VoiceProcessor* voice_processor,
1479 MediaProcessorDirection direction) {
1480 bool register_with_webrtc = false;
1481 int channel_id = -1;
1482 bool success = false;
1483 uint32* processor_ssrc = NULL;
1484 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1485 if (voice_processor == NULL || !found_channel) {
1486 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1487 << " foundChannel: " << found_channel;
1488 return false;
1489 }
1490
1491 webrtc::ProcessingTypes processing_type;
1492 {
1493 talk_base::CritScope cs(&signal_media_critical_);
1494 if (direction == MPD_RX) {
1495 processing_type = webrtc::kPlaybackAllChannelsMixed;
1496 if (SignalRxMediaFrame.is_empty()) {
1497 register_with_webrtc = true;
1498 processor_ssrc = &rx_processor_ssrc_;
1499 }
1500 SignalRxMediaFrame.connect(voice_processor,
1501 &VoiceProcessor::OnFrame);
1502 } else {
1503 processing_type = webrtc::kRecordingPerChannel;
1504 if (SignalTxMediaFrame.is_empty()) {
1505 register_with_webrtc = true;
1506 processor_ssrc = &tx_processor_ssrc_;
1507 }
1508 SignalTxMediaFrame.connect(voice_processor,
1509 &VoiceProcessor::OnFrame);
1510 }
1511 }
1512 if (register_with_webrtc) {
1513 // TODO(janahan): when registering consider instantiating a
1514 // a VoeMediaProcess object and not make the engine extend the interface.
1515 if (voe()->media() && voe()->media()->
1516 RegisterExternalMediaProcessing(channel_id,
1517 processing_type,
1518 *this) != -1) {
1519 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1520 << channel_id;
1521 *processor_ssrc = ssrc;
1522 success = true;
1523 } else {
1524 LOG_RTCERR2(RegisterExternalMediaProcessing,
1525 channel_id,
1526 processing_type);
1527 success = false;
1528 }
1529 } else {
1530 // If we don't have to register with the engine, we just needed to
1531 // connect a new processor, set success to true;
1532 success = true;
1533 }
1534 return success;
1535}
1536
1537bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1538 MediaProcessorDirection channel_direction,
1539 uint32 ssrc,
1540 VoiceProcessor* voice_processor,
1541 MediaProcessorDirection processor_direction) {
1542 bool success = true;
1543 FrameSignal* signal;
1544 webrtc::ProcessingTypes processing_type;
1545 uint32* processor_ssrc = NULL;
1546 if (channel_direction == MPD_RX) {
1547 signal = &SignalRxMediaFrame;
1548 processing_type = webrtc::kPlaybackAllChannelsMixed;
1549 processor_ssrc = &rx_processor_ssrc_;
1550 } else {
1551 signal = &SignalTxMediaFrame;
1552 processing_type = webrtc::kRecordingPerChannel;
1553 processor_ssrc = &tx_processor_ssrc_;
1554 }
1555
1556 int deregister_id = -1;
1557 {
1558 talk_base::CritScope cs(&signal_media_critical_);
1559 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1560 signal->disconnect(voice_processor);
1561 int channel_id = -1;
1562 bool found_channel = FindChannelNumFromSsrc(ssrc,
1563 channel_direction,
1564 &channel_id);
1565 if (signal->is_empty() && found_channel) {
1566 deregister_id = channel_id;
1567 }
1568 }
1569 }
1570 if (deregister_id != -1) {
1571 if (voe()->media() &&
1572 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1573 processing_type) != -1) {
1574 *processor_ssrc = 0;
1575 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1576 << deregister_id;
1577 } else {
1578 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1579 deregister_id,
1580 processing_type);
1581 success = false;
1582 }
1583 }
1584 return success;
1585}
1586
1587bool WebRtcVoiceEngine::UnregisterProcessor(
1588 uint32 ssrc,
1589 VoiceProcessor* voice_processor,
1590 MediaProcessorDirection direction) {
1591 bool success = true;
1592 if (voice_processor == NULL) {
1593 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1594 << ssrc;
1595 return false;
1596 }
1597 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1598 success = false;
1599 }
1600 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1601 success = false;
1602 }
1603 return success;
1604}
1605
1606// Implementing method from WebRtc VoEMediaProcess interface
1607// Do not lock mux_channel_cs_ in this callback.
1608void WebRtcVoiceEngine::Process(int channel,
1609 webrtc::ProcessingTypes type,
1610 int16_t audio10ms[],
1611 int length,
1612 int sampling_freq,
1613 bool is_stereo) {
1614 talk_base::CritScope cs(&signal_media_critical_);
1615 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1616 if (type == webrtc::kPlaybackAllChannelsMixed) {
1617 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1618 } else if (type == webrtc::kRecordingPerChannel) {
1619 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1620 } else {
1621 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1622 << " channel: " << channel << " type: " << type
1623 << " tx_ssrc: " << tx_processor_ssrc_
1624 << " rx_ssrc: " << rx_processor_ssrc_;
1625 }
1626}
1627
1628void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1629 if (!is_dumping_aec_) {
1630 // Start dumping AEC when we are not dumping.
1631 if (voe_wrapper_->processing()->StartDebugRecording(
1632 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001633 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 } else {
1635 is_dumping_aec_ = true;
1636 }
1637 }
1638}
1639
1640void WebRtcVoiceEngine::StopAecDump() {
1641 if (is_dumping_aec_) {
1642 // Stop dumping AEC when we are dumping.
1643 if (voe_wrapper_->processing()->StopDebugRecording() !=
1644 webrtc::AudioProcessing::kNoError) {
1645 LOG_RTCERR0(StopDebugRecording);
1646 }
1647 is_dumping_aec_ = false;
1648 }
1649}
1650
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001651int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001652 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001653}
1654
1655int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1656 return CreateVoiceChannel(voe_wrapper_.get());
1657}
1658
1659int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1660 return CreateVoiceChannel(voe_wrapper_sc_.get());
1661}
1662
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001663class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1664 : public AudioRenderer::Sink {
1665 public:
1666 WebRtcVoiceChannelRenderer(int ch,
1667 webrtc::AudioTransport* voe_audio_transport)
1668 : channel_(ch),
1669 voe_audio_transport_(voe_audio_transport),
1670 renderer_(NULL) {
1671 }
1672 virtual ~WebRtcVoiceChannelRenderer() {
1673 Stop();
1674 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001675
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001676 // Starts the rendering by setting a sink to the renderer to get data
1677 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001678 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001679 // TODO(xians): Make sure Start() is called only once.
1680 void Start(AudioRenderer* renderer) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001681 talk_base::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001682 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001683 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001684 ASSERT(renderer_ == renderer);
1685 return;
1686 }
1687
1688 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1689 // in getUserMedia by default.
1690 renderer->AddChannel(channel_);
1691 renderer->SetSink(this);
1692 renderer_ = renderer;
1693 }
1694
1695 // Stops rendering by setting the sink of the renderer to NULL. No data
1696 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001697 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001698 void Stop() {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001699 talk_base::CritScope lock(&lock_);
1700 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001701 return;
1702
1703 renderer_->RemoveChannel(channel_);
1704 renderer_->SetSink(NULL);
1705 renderer_ = NULL;
1706 }
1707
1708 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001709 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001710 virtual void OnData(const void* audio_data,
1711 int bits_per_sample,
1712 int sample_rate,
1713 int number_of_channels,
1714 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001715#ifdef USE_WEBRTC_DEV_BRANCH
1716 voe_audio_transport_->OnData(channel_,
1717 audio_data,
1718 bits_per_sample,
1719 sample_rate,
1720 number_of_channels,
1721 number_of_frames);
1722#endif
1723 }
1724
1725 // Callback from the |renderer_| when it is going away. In case Start() has
1726 // never been called, this callback won't be triggered.
1727 virtual void OnClose() OVERRIDE {
1728 talk_base::CritScope lock(&lock_);
1729 // Set |renderer_| to NULL to make sure no more callback will get into
1730 // the renderer.
1731 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001732 }
1733
1734 // Accessor to the VoE channel ID.
1735 int channel() const { return channel_; }
1736
1737 private:
1738 const int channel_;
1739 webrtc::AudioTransport* const voe_audio_transport_;
1740
1741 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1742 // PeerConnection will make sure invalidating the pointer before the object
1743 // goes away.
1744 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001745
1746 // Protects |renderer_| in Start(), Stop() and OnClose().
1747 talk_base::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001748};
1749
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750// WebRtcVoiceMediaChannel
1751WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1752 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1753 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001754 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001755 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001756 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 options_(),
1758 dtmf_allowed_(false),
1759 desired_playout_(false),
1760 nack_enabled_(false),
1761 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001762 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 desired_send_(SEND_NOTHING),
1764 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765 default_receive_ssrc_(0) {
1766 engine->RegisterChannel(this);
1767 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1768 << voe_channel();
1769
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001770 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771}
1772
1773WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1774 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1775 << voe_channel();
1776
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001777 // Remove any remaining send streams, the default channel will be deleted
1778 // later.
1779 while (!send_channels_.empty())
1780 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781
1782 // Unregister ourselves from the engine.
1783 engine()->UnregisterChannel(this);
1784 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001785 while (!receive_channels_.empty()) {
1786 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 }
1788
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001789 // Delete the default channel.
1790 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001791}
1792
1793bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1794 LOG(LS_INFO) << "Setting voice channel options: "
1795 << options.ToString();
1796
wu@webrtc.orgde305012013-10-31 15:40:38 +00001797 // Check if DSCP value is changed from previous.
1798 bool dscp_option_changed = (options_.dscp != options.dscp);
1799
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001800 // TODO(xians): Add support to set different options for different send
1801 // streams after we support multiple APMs.
1802
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 // We retain all of the existing options, and apply the given ones
1804 // on top. This means there is no way to "clear" options such that
1805 // they go back to the engine default.
1806 options_.SetAll(options);
1807
1808 if (send_ != SEND_NOTHING) {
1809 if (!engine()->SetOptionOverrides(options_)) {
1810 LOG(LS_WARNING) <<
1811 "Failed to engine SetOptionOverrides during channel SetOptions.";
1812 return false;
1813 }
1814 } else {
1815 // Will be interpreted when appropriate.
1816 }
1817
wu@webrtc.org97077a32013-10-25 21:18:33 +00001818 // Receiver-side auto gain control happens per channel, so set it here from
1819 // options. Note that, like conference mode, setting it on the engine won't
1820 // have the desired effect, since voice channels don't inherit options from
1821 // the media engine when those options are applied per-channel.
1822 bool rx_auto_gain_control;
1823 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1824 if (engine()->voe()->processing()->SetRxAgcStatus(
1825 voe_channel(), rx_auto_gain_control,
1826 webrtc::kAgcFixedDigital) == -1) {
1827 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1828 return false;
1829 } else {
1830 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1831 << " with mode " << webrtc::kAgcFixedDigital;
1832 }
1833 }
1834 if (options.rx_agc_target_dbov.IsSet() ||
1835 options.rx_agc_digital_compression_gain.IsSet() ||
1836 options.rx_agc_limiter.IsSet()) {
1837 webrtc::AgcConfig config;
1838 // If only some of the options are being overridden, get the current
1839 // settings for the channel and bail if they aren't available.
1840 if (!options.rx_agc_target_dbov.IsSet() ||
1841 !options.rx_agc_digital_compression_gain.IsSet() ||
1842 !options.rx_agc_limiter.IsSet()) {
1843 if (engine()->voe()->processing()->GetRxAgcConfig(
1844 voe_channel(), config) != 0) {
1845 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1846 << "channel " << voe_channel() << ". Since not all rx "
1847 << "agc options are specified, unable to safely set rx "
1848 << "agc options.";
1849 return false;
1850 }
1851 }
1852 config.targetLeveldBOv =
1853 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1854 config.targetLeveldBOv);
1855 config.digitalCompressionGaindB =
1856 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1857 config.digitalCompressionGaindB);
1858 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1859 config.limiterEnable);
1860 if (engine()->voe()->processing()->SetRxAgcConfig(
1861 voe_channel(), config) == -1) {
1862 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1863 config.digitalCompressionGaindB, config.limiterEnable);
1864 return false;
1865 }
1866 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001867 if (dscp_option_changed) {
1868 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001869 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001870 dscp = kAudioDscpValue;
1871 if (MediaChannel::SetDscp(dscp) != 0) {
1872 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1873 }
1874 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001875
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001876 LOG(LS_INFO) << "Set voice channel options. Current options: "
1877 << options_.ToString();
1878 return true;
1879}
1880
1881bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1882 const std::vector<AudioCodec>& codecs) {
1883 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 LOG(LS_INFO) << "Setting receive voice codecs:";
1885
1886 std::vector<AudioCodec> new_codecs;
1887 // Find all new codecs. We allow adding new codecs but don't allow changing
1888 // the payload type of codecs that is already configured since we might
1889 // already be receiving packets with that payload type.
1890 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001891 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 AudioCodec old_codec;
1893 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1894 if (old_codec.id != it->id) {
1895 LOG(LS_ERROR) << it->name << " payload type changed.";
1896 return false;
1897 }
1898 } else {
1899 new_codecs.push_back(*it);
1900 }
1901 }
1902 if (new_codecs.empty()) {
1903 // There are no new codecs to configure. Already configured codecs are
1904 // never removed.
1905 return true;
1906 }
1907
1908 if (playout_) {
1909 // Receive codecs can not be changed while playing. So we temporarily
1910 // pause playout.
1911 PausePlayout();
1912 }
1913
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001914 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1916 it != new_codecs.end() && ret; ++it) {
1917 webrtc::CodecInst voe_codec;
1918 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1919 LOG(LS_INFO) << ToString(*it);
1920 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001921 if (default_receive_ssrc_ == 0) {
1922 // Set the receive codecs on the default channel explicitly if the
1923 // default channel is not used by |receive_channels_|, this happens in
1924 // conference mode or in non-conference mode when there is no playout
1925 // channel.
1926 // TODO(xians): Figure out how we use the default channel in conference
1927 // mode.
1928 if (engine()->voe()->codec()->SetRecPayloadType(
1929 voe_channel(), voe_codec) == -1) {
1930 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1931 ret = false;
1932 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 }
1934
1935 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001936 for (ChannelMap::iterator it = receive_channels_.begin();
1937 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001939 it->second->channel(), voe_codec) == -1) {
1940 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001941 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942 ret = false;
1943 }
1944 }
1945 } else {
1946 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1947 ret = false;
1948 }
1949 }
1950 if (ret) {
1951 recv_codecs_ = codecs;
1952 }
1953
1954 if (desired_playout_ && !playout_) {
1955 ResumePlayout();
1956 }
1957 return ret;
1958}
1959
1960bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001961 int channel, const std::vector<AudioCodec>& codecs) {
1962 // Disable VAD, and FEC unless we know the other side wants them.
1963 engine()->voe()->codec()->SetVADStatus(channel, false);
1964 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1965 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966
1967 // Scan through the list to figure out the codec to use for sending, along
1968 // with the proper configuration for VAD and DTMF.
1969 bool first = true;
1970 webrtc::CodecInst send_codec;
1971 memset(&send_codec, 0, sizeof(send_codec));
1972
1973 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1974 it != codecs.end(); ++it) {
1975 // Ignore codecs we don't know about. The negotiation step should prevent
1976 // this, but double-check to be sure.
1977 webrtc::CodecInst voe_codec;
1978 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001979 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 continue;
1981 }
1982
1983 // If OPUS, change what we send according to the "stereo" codec
1984 // parameter, and not the "channels" parameter. We set
1985 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1986 // the bitrate is not specified, i.e. is zero, we set it to the
1987 // appropriate default value for mono or stereo Opus.
1988 if (IsOpus(*it)) {
1989 if (IsOpusStereoEnabled(*it)) {
1990 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001991 if (!IsValidOpusBitrate(it->bitrate)) {
1992 if (it->bitrate != 0) {
1993 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1994 << it->bitrate
1995 << ") with default opus stereo bitrate: "
1996 << kOpusStereoBitrate;
1997 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 voe_codec.rate = kOpusStereoBitrate;
1999 }
2000 } else {
2001 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002002 if (!IsValidOpusBitrate(it->bitrate)) {
2003 if (it->bitrate != 0) {
2004 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2005 << it->bitrate
2006 << ") with default opus mono bitrate: "
2007 << kOpusMonoBitrate;
2008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 voe_codec.rate = kOpusMonoBitrate;
2010 }
2011 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002012 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2013 if (bitrate_from_params != 0) {
2014 voe_codec.rate = bitrate_from_params;
2015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016 }
2017
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002018 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2019 // about it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002020 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2021 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002022 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2023 channel, it->id) == -1) {
2024 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2025 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 }
2028
2029 // Turn voice activity detection/comfort noise on if supported.
2030 // Set the wideband CN payload type appropriately.
2031 // (narrowband always uses the static payload type 13).
2032 if (_stricmp(it->name.c_str(), "CN") == 0) {
2033 webrtc::PayloadFrequencies cn_freq;
2034 switch (it->clockrate) {
2035 case 8000:
2036 cn_freq = webrtc::kFreq8000Hz;
2037 break;
2038 case 16000:
2039 cn_freq = webrtc::kFreq16000Hz;
2040 break;
2041 case 32000:
2042 cn_freq = webrtc::kFreq32000Hz;
2043 break;
2044 default:
2045 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2046 << " not supported.";
2047 continue;
2048 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002049 // Set the CN payloadtype and the VAD status.
2050 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2051 if (cn_freq != webrtc::kFreq8000Hz) {
2052 if (engine()->voe()->codec()->SetSendCNPayloadType(
2053 channel, it->id, cn_freq) == -1) {
2054 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2055 // TODO(ajm): This failure condition will be removed from VoE.
2056 // Restore the return here when we update to a new enough webrtc.
2057 //
2058 // Not returning false because the SetSendCNPayloadType will fail if
2059 // the channel is already sending.
2060 // This can happen if the remote description is applied twice, for
2061 // example in the case of ROAP on top of JSEP, where both side will
2062 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002064 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002065
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002066 // Only turn on VAD if we have a CN payload type that matches the
2067 // clockrate for the codec we are going to use.
2068 if (it->clockrate == send_codec.plfreq) {
2069 LOG(LS_INFO) << "Enabling VAD";
2070 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2071 LOG_RTCERR2(SetVADStatus, channel, true);
2072 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073 }
2074 }
2075 }
2076
2077 // We'll use the first codec in the list to actually send audio data.
2078 // Be sure to use the payload type requested by the remote side.
2079 // "red", for FEC audio, is a special case where the actual codec to be
2080 // used is specified in params.
2081 if (first) {
2082 if (_stricmp(it->name.c_str(), "red") == 0) {
2083 // Parse out the RED parameters. If we fail, just ignore RED;
2084 // we don't support all possible params/usage scenarios.
2085 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2086 continue;
2087 }
2088
2089 // Enable redundant encoding of the specified codec. Treat any
2090 // failure as a fatal internal error.
2091 LOG(LS_INFO) << "Enabling FEC";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002092 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2093 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2094 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095 }
2096 } else {
2097 send_codec = voe_codec;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002098 nack_enabled_ = IsNackEnabled(*it);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002099 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 }
2101 first = false;
2102 // Set the codec immediately, since SetVADStatus() depends on whether
2103 // the current codec is mono or stereo.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002104 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105 return false;
2106 }
2107 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108
2109 // If we're being asked to set an empty list of codecs, due to a buggy client,
2110 // choose the most common format: PCMU
2111 if (first) {
2112 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
2113 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
2114 engine()->FindWebRtcCodec(codec, &send_codec);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002115 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002116 return false;
2117 }
2118
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002119 // Always update the |send_codec_| to the currently set send codec.
2120 send_codec_.reset(new webrtc::CodecInst(send_codec));
2121
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002122 if (send_bw_setting_) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002123 SetSendBandwidthInternal(send_bw_bps_);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002124 }
2125
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002126 return true;
2127}
2128
2129bool WebRtcVoiceMediaChannel::SetSendCodecs(
2130 const std::vector<AudioCodec>& codecs) {
2131 dtmf_allowed_ = false;
2132 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2133 it != codecs.end(); ++it) {
2134 // Find the DTMF telephone event "codec".
2135 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2136 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2137 dtmf_allowed_ = true;
2138 }
2139 }
2140
2141 // Cache the codecs in order to configure the channel created later.
2142 send_codecs_ = codecs;
2143 for (ChannelMap::iterator iter = send_channels_.begin();
2144 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002145 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002146 return false;
2147 }
2148 }
2149
2150 SetNack(receive_channels_, nack_enabled_);
2151
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152 return true;
2153}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002154
2155void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2156 bool nack_enabled) {
2157 for (ChannelMap::const_iterator it = channels.begin();
2158 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002159 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002160 }
2161}
2162
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002163void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002165 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2167 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002168 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2170 }
2171}
2172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173bool WebRtcVoiceMediaChannel::SetSendCodec(
2174 const webrtc::CodecInst& send_codec) {
2175 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2176 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002177 for (ChannelMap::iterator iter = send_channels_.begin();
2178 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002179 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002180 return false;
2181 }
2182
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002183 return true;
2184}
2185
2186bool WebRtcVoiceMediaChannel::SetSendCodec(
2187 int channel, const webrtc::CodecInst& send_codec) {
2188 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2189 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2190
2191 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2192 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 return false;
2194 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002195 return true;
2196}
2197
2198bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2199 const std::vector<RtpHeaderExtension>& extensions) {
2200 // We don't support any incoming extensions headers right now.
2201 return true;
2202}
2203
2204bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2205 const std::vector<RtpHeaderExtension>& extensions) {
2206 // Enable the audio level extension header if requested.
2207 std::vector<RtpHeaderExtension>::const_iterator it;
2208 for (it = extensions.begin(); it != extensions.end(); ++it) {
2209 if (it->uri == kRtpAudioLevelHeaderExtension) {
2210 break;
2211 }
2212 }
2213
2214 bool enable = (it != extensions.end());
2215 int id = 0;
2216
2217 if (enable) {
2218 id = it->id;
2219 if (id < kMinRtpHeaderExtensionId ||
2220 id > kMaxRtpHeaderExtensionId) {
2221 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2222 return false;
2223 }
2224 }
2225
2226 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002227 for (ChannelMap::const_iterator iter = send_channels_.begin();
2228 iter != send_channels_.end(); ++iter) {
2229 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002230 iter->second->channel(), enable, id) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002231 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002232 iter->second->channel(), enable, id);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002233 return false;
2234 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 }
2236
2237 return true;
2238}
2239
2240bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2241 desired_playout_ = playout;
2242 return ChangePlayout(desired_playout_);
2243}
2244
2245bool WebRtcVoiceMediaChannel::PausePlayout() {
2246 return ChangePlayout(false);
2247}
2248
2249bool WebRtcVoiceMediaChannel::ResumePlayout() {
2250 return ChangePlayout(desired_playout_);
2251}
2252
2253bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2254 if (playout_ == playout) {
2255 return true;
2256 }
2257
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002258 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002260 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 // Only toggle the default channel if we don't have any other channels.
2262 result = SetPlayout(voe_channel(), playout);
2263 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002264 for (ChannelMap::iterator it = receive_channels_.begin();
2265 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002266 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002267 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002268 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269 result = false;
2270 }
2271 }
2272
2273 if (result) {
2274 playout_ = playout;
2275 }
2276 return result;
2277}
2278
2279bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2280 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002281 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 return ChangeSend(desired_send_);
2283 return true;
2284}
2285
2286bool WebRtcVoiceMediaChannel::PauseSend() {
2287 return ChangeSend(SEND_NOTHING);
2288}
2289
2290bool WebRtcVoiceMediaChannel::ResumeSend() {
2291 return ChangeSend(desired_send_);
2292}
2293
2294bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2295 if (send_ == send) {
2296 return true;
2297 }
2298
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002299 // Change the settings on each send channel.
2300 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002301 engine()->SetOptionOverrides(options_);
2302
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002303 // Change the settings on each send channel.
2304 for (ChannelMap::iterator iter = send_channels_.begin();
2305 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002306 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002309
2310 // Clear up the options after stopping sending.
2311 if (send == SEND_NOTHING)
2312 engine()->ClearOptionOverrides();
2313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314 send_ = send;
2315 return true;
2316}
2317
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002318bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2319 if (send == SEND_MICROPHONE) {
2320 if (engine()->voe()->base()->StartSend(channel) == -1) {
2321 LOG_RTCERR1(StartSend, channel);
2322 return false;
2323 }
2324 if (engine()->voe()->file() &&
2325 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2326 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2327 return false;
2328 }
2329 } else { // SEND_NOTHING
2330 ASSERT(send == SEND_NOTHING);
2331 if (engine()->voe()->base()->StopSend(channel) == -1) {
2332 LOG_RTCERR1(StopSend, channel);
2333 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334 }
2335 }
2336
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 return true;
2338}
2339
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002340void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2341 if (engine()->voe()->network()->RegisterExternalTransport(
2342 channel, *this) == -1) {
2343 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2344 }
2345
2346 // Enable RTCP (for quality stats and feedback messages)
2347 EnableRtcp(channel);
2348
2349 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2350 ResetRecvCodecs(channel);
2351}
2352
2353bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2354 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2355 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2356 }
2357
2358 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2359 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 return false;
2361 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002362
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002363 return true;
2364}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002365
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002366bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2367 // If the default channel is already used for sending create a new channel
2368 // otherwise use the default channel for sending.
2369 int channel = GetSendChannelNum(sp.first_ssrc());
2370 if (channel != -1) {
2371 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2372 return false;
2373 }
2374
2375 bool default_channel_is_available = true;
2376 for (ChannelMap::const_iterator iter = send_channels_.begin();
2377 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002378 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002379 default_channel_is_available = false;
2380 break;
2381 }
2382 }
2383 if (default_channel_is_available) {
2384 channel = voe_channel();
2385 } else {
2386 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002387 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002388 if (channel == -1) {
2389 LOG_RTCERR0(CreateChannel);
2390 return false;
2391 }
2392
2393 ConfigureSendChannel(channel);
2394 }
2395
2396 // Save the channel to send_channels_, so that RemoveSendStream() can still
2397 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002398#ifdef USE_WEBRTC_DEV_BRANCH
2399 webrtc::AudioTransport* audio_transport =
2400 engine()->voe()->base()->audio_transport();
2401#else
2402 webrtc::AudioTransport* audio_transport = NULL;
2403#endif
2404 send_channels_.insert(std::make_pair(
2405 sp.first_ssrc(),
2406 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002407
2408 // Set the send (local) SSRC.
2409 // If there are multiple send SSRCs, we can only set the first one here, and
2410 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2411 // (with a codec requires multiple SSRC(s)).
2412 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2413 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2414 return false;
2415 }
2416
2417 // At this point the channel's local SSRC has been updated. If the channel is
2418 // the default channel make sure that all the receive channels are updated as
2419 // well. Receive channels have to have the same SSRC as the default channel in
2420 // order to send receiver reports with this SSRC.
2421 if (IsDefaultChannel(channel)) {
2422 for (ChannelMap::const_iterator it = receive_channels_.begin();
2423 it != receive_channels_.end(); ++it) {
2424 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002425 if (!IsDefaultChannel(it->second->channel())) {
2426 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002427 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002428 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002429 return false;
2430 }
2431 }
2432 }
2433 }
2434
2435 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2436 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2437 return false;
2438 }
2439
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002440 // Set the current codecs to be used for the new channel.
2441 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002442 return false;
2443
2444 return ChangeSend(channel, desired_send_);
2445}
2446
2447bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2448 ChannelMap::iterator it = send_channels_.find(ssrc);
2449 if (it == send_channels_.end()) {
2450 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2451 << " which doesn't exist.";
2452 return false;
2453 }
2454
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002455 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002456 ChangeSend(channel, SEND_NOTHING);
2457
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002458 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2459 // this will disconnect the audio renderer with the send channel.
2460 delete it->second;
2461 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462
2463 if (IsDefaultChannel(channel)) {
2464 // Do not delete the default channel since the receive channels depend on
2465 // the default channel, recycle it instead.
2466 ChangeSend(channel, SEND_NOTHING);
2467 } else {
2468 // Clean up and delete the send channel.
2469 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2470 << " with VoiceEngine channel #" << channel << ".";
2471 if (!DeleteChannel(channel))
2472 return false;
2473 }
2474
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002475 if (send_channels_.empty())
2476 ChangeSend(SEND_NOTHING);
2477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 return true;
2479}
2480
2481bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002482 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002483
2484 if (!VERIFY(sp.ssrcs.size() == 1))
2485 return false;
2486 uint32 ssrc = sp.first_ssrc();
2487
wu@webrtc.org78187522013-10-07 23:32:02 +00002488 if (ssrc == 0) {
2489 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2490 return false;
2491 }
2492
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002493 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2494 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 return false;
2496 }
2497
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002498 // Reuse default channel for recv stream in non-conference mode call
2499 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002500#ifdef USE_WEBRTC_DEV_BRANCH
2501 webrtc::AudioTransport* audio_transport =
2502 engine()->voe()->base()->audio_transport();
2503#else
2504 webrtc::AudioTransport* audio_transport = NULL;
2505#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002506 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2507 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2508 << " reuse default channel";
2509 default_receive_ssrc_ = sp.first_ssrc();
2510 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002511 default_receive_ssrc_,
2512 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002513 return SetPlayout(voe_channel(), playout_);
2514 }
2515
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002517 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 if (channel == -1) {
2519 LOG_RTCERR0(CreateChannel);
2520 return false;
2521 }
2522
wu@webrtc.org78187522013-10-07 23:32:02 +00002523 if (!ConfigureRecvChannel(channel)) {
2524 DeleteChannel(channel);
2525 return false;
2526 }
2527
2528 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002529 std::make_pair(
2530 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002531
2532 LOG(LS_INFO) << "New audio stream " << ssrc
2533 << " registered to VoiceEngine channel #"
2534 << channel << ".";
2535 return true;
2536}
2537
2538bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002539 // Configure to use external transport, like our default channel.
2540 if (engine()->voe()->network()->RegisterExternalTransport(
2541 channel, *this) == -1) {
2542 LOG_RTCERR2(SetExternalTransport, channel, this);
2543 return false;
2544 }
2545
2546 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002547 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2549 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002550 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002551 return false;
2552 }
2553 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002554 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002555 return false;
2556 }
2557
2558 // Use the same recv payload types as our default channel.
2559 ResetRecvCodecs(channel);
2560 if (!recv_codecs_.empty()) {
2561 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2562 it != recv_codecs_.end(); ++it) {
2563 webrtc::CodecInst voe_codec;
2564 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2565 voe_codec.pltype = it->id;
2566 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2567 if (engine()->voe()->codec()->GetRecPayloadType(
2568 voe_channel(), voe_codec) != -1) {
2569 if (engine()->voe()->codec()->SetRecPayloadType(
2570 channel, voe_codec) == -1) {
2571 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2572 return false;
2573 }
2574 }
2575 }
2576 }
2577 }
2578
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002579 if (InConferenceMode()) {
2580 // To be in par with the video, voe_channel() is not used for receiving in
2581 // a conference call.
2582 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2583 // This is the first stream in a multi user meeting. We can now
2584 // disable playback of the default stream. This since the default
2585 // stream will probably have received some initial packets before
2586 // the new stream was added. This will mean that the CN state from
2587 // the default channel will be mixed in with the other streams
2588 // throughout the whole meeting, which might be disturbing.
2589 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2590 SetPlayout(voe_channel(), false);
2591 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002593 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002595 return SetPlayout(channel, playout_);
2596}
2597
2598bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002599 talk_base::CritScope lock(&receive_channels_cs_);
2600 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002601 if (it == receive_channels_.end()) {
2602 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2603 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002604 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002605 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002607 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2608 // will disconnect the audio renderer with the receive channel.
2609 // Cache the channel before the deletion.
2610 const int channel = it->second->channel();
2611 delete it->second;
2612 receive_channels_.erase(it);
2613
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002614 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002615 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002616 // Recycle the default channel is for recv stream.
2617 if (playout_)
2618 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002620 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002621 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002622 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002623
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002624 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002625 << " with VoiceEngine channel #" << channel << ".";
2626 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002627 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002628
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002629 bool enable_default_channel_playout = false;
2630 if (receive_channels_.empty()) {
2631 // The last stream was removed. We can now enable the default
2632 // channel for new channels to be played out immediately without
2633 // waiting for AddStream messages.
2634 // We do this for both conference mode and non-conference mode.
2635 // TODO(oja): Does the default channel still have it's CN state?
2636 enable_default_channel_playout = true;
2637 }
2638 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2639 default_receive_ssrc_ != 0) {
2640 // Only the default channel is active, enable the playout on default
2641 // channel.
2642 enable_default_channel_playout = true;
2643 }
2644 if (enable_default_channel_playout && playout_) {
2645 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2646 SetPlayout(voe_channel(), true);
2647 }
2648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002649 return true;
2650}
2651
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002652bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2653 AudioRenderer* renderer) {
2654 ChannelMap::iterator it = receive_channels_.find(ssrc);
2655 if (it == receive_channels_.end()) {
2656 if (renderer) {
2657 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002658 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002659 return false;
2660 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002662 // The channel likely has gone away, do nothing.
2663 return true;
2664 }
2665
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002666 if (renderer)
2667 it->second->Start(renderer);
2668 else
2669 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002670
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671 return true;
2672}
2673
2674bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2675 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002676 ChannelMap::iterator it = send_channels_.find(ssrc);
2677 if (it == send_channels_.end()) {
2678 if (renderer) {
2679 // Return an error if trying to set a valid renderer with an invalid ssrc.
2680 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2681 return false;
2682 }
2683
2684 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002685 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002686 }
2687
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002688 if (renderer)
2689 it->second->Start(renderer);
2690 else
2691 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002693 return true;
2694}
2695
2696bool WebRtcVoiceMediaChannel::GetActiveStreams(
2697 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002698 // In conference mode, the default channel should not be in
2699 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002700 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002701 for (ChannelMap::iterator it = receive_channels_.begin();
2702 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002703 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 if (level > 0) {
2705 actives->push_back(std::make_pair(it->first, level));
2706 }
2707 }
2708 return true;
2709}
2710
2711int WebRtcVoiceMediaChannel::GetOutputLevel() {
2712 // return the highest output level of all streams
2713 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002714 for (ChannelMap::iterator it = receive_channels_.begin();
2715 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002716 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 highest = talk_base::_max(level, highest);
2718 }
2719 return highest;
2720}
2721
2722int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2723 int ret;
2724 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2725 // In case of error, log the info and continue
2726 LOG_RTCERR0(TimeSinceLastTyping);
2727 ret = -1;
2728 } else {
2729 ret *= 1000; // We return ms, webrtc returns seconds.
2730 }
2731 return ret;
2732}
2733
2734void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2735 int cost_per_typing, int reporting_threshold, int penalty_decay,
2736 int type_event_delay) {
2737 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2738 time_window, cost_per_typing,
2739 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2740 // In case of error, log the info and continue
2741 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2742 cost_per_typing, reporting_threshold, penalty_decay,
2743 type_event_delay);
2744 }
2745}
2746
2747bool WebRtcVoiceMediaChannel::SetOutputScaling(
2748 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002749 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002750 // Collect the channels to scale the output volume.
2751 std::vector<int> channels;
2752 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002753 // Default channel is not in receive_channels_ if it is not being used for
2754 // playout.
2755 if (default_receive_ssrc_ == 0)
2756 channels.push_back(voe_channel());
2757 for (ChannelMap::const_iterator it = receive_channels_.begin();
2758 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002759 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760 }
2761 } else { // Collect only the channel of the specified ssrc.
2762 int channel = GetReceiveChannelNum(ssrc);
2763 if (-1 == channel) {
2764 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2765 return false;
2766 }
2767 channels.push_back(channel);
2768 }
2769
2770 // Scale the output volume for the collected channels. We first normalize to
2771 // scale the volume and then set the left and right pan.
2772 float scale = static_cast<float>(talk_base::_max(left, right));
2773 if (scale > 0.0001f) {
2774 left /= scale;
2775 right /= scale;
2776 }
2777 for (std::vector<int>::const_iterator it = channels.begin();
2778 it != channels.end(); ++it) {
2779 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2780 *it, scale)) {
2781 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2782 return false;
2783 }
2784 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2785 *it, static_cast<float>(left), static_cast<float>(right))) {
2786 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2787 // Do not return if fails. SetOutputVolumePan is not available for all
2788 // pltforms.
2789 }
2790 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2791 << " right=" << right * scale
2792 << " for channel " << *it << " and ssrc " << ssrc;
2793 }
2794 return true;
2795}
2796
2797bool WebRtcVoiceMediaChannel::GetOutputScaling(
2798 uint32 ssrc, double* left, double* right) {
2799 if (!left || !right) return false;
2800
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002801 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 // Determine which channel based on ssrc.
2803 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2804 if (channel == -1) {
2805 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2806 return false;
2807 }
2808
2809 float scaling;
2810 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2811 channel, scaling)) {
2812 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2813 return false;
2814 }
2815
2816 float left_pan;
2817 float right_pan;
2818 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2819 channel, left_pan, right_pan)) {
2820 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2821 // If GetOutputVolumePan fails, we use the default left and right pan.
2822 left_pan = 1.0f;
2823 right_pan = 1.0f;
2824 }
2825
2826 *left = scaling * left_pan;
2827 *right = scaling * right_pan;
2828 return true;
2829}
2830
2831bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2832 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2833 return true;
2834}
2835
2836bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2837 bool play, bool loop) {
2838 if (!ringback_tone_) {
2839 return false;
2840 }
2841
2842 // The voe file api is not available in chrome.
2843 if (!engine()->voe()->file()) {
2844 return false;
2845 }
2846
2847 // Determine which VoiceEngine channel to play on.
2848 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2849 if (channel == -1) {
2850 return false;
2851 }
2852
2853 // Make sure the ringtone is cued properly, and play it out.
2854 if (play) {
2855 ringback_tone_->set_loop(loop);
2856 ringback_tone_->Rewind();
2857 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2858 ringback_tone_.get()) == -1) {
2859 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2860 LOG(LS_ERROR) << "Unable to start ringback tone";
2861 return false;
2862 }
2863 ringback_channels_.insert(channel);
2864 LOG(LS_INFO) << "Started ringback on channel " << channel;
2865 } else {
2866 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2867 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2868 LOG_RTCERR1(StopPlayingFileLocally, channel);
2869 return false;
2870 }
2871 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2872 ringback_channels_.erase(channel);
2873 }
2874
2875 return true;
2876}
2877
2878bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2879 return dtmf_allowed_;
2880}
2881
2882bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2883 int duration, int flags) {
2884 if (!dtmf_allowed_) {
2885 return false;
2886 }
2887
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002888 // Send the event.
2889 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002890 int channel = -1;
2891 if (ssrc == 0) {
2892 bool default_channel_is_inuse = false;
2893 for (ChannelMap::const_iterator iter = send_channels_.begin();
2894 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002895 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002896 default_channel_is_inuse = true;
2897 break;
2898 }
2899 }
2900 if (default_channel_is_inuse) {
2901 channel = voe_channel();
2902 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002903 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002904 }
2905 } else {
2906 channel = GetSendChannelNum(ssrc);
2907 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002908 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2910 << ssrc << " is not in use.";
2911 return false;
2912 }
2913 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002914 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2915 channel, event, true, duration) == -1) {
2916 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 return false;
2918 }
2919 }
2920
2921 // Play the event.
2922 if (flags & cricket::DF_PLAY) {
2923 // Play DTMF tone locally.
2924 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2925 LOG_RTCERR2(PlayDtmfTone, event, duration);
2926 return false;
2927 }
2928 }
2929
2930 return true;
2931}
2932
wu@webrtc.orga9890802013-12-13 00:21:03 +00002933void WebRtcVoiceMediaChannel::OnPacketReceived(
2934 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 // Pick which channel to send this packet to. If this packet doesn't match
2936 // any multiplexed streams, just send it to the default channel. Otherwise,
2937 // send it to the specific decoder instance for that stream.
2938 int which_channel = GetReceiveChannelNum(
2939 ParseSsrc(packet->data(), packet->length(), false));
2940 if (which_channel == -1) {
2941 which_channel = voe_channel();
2942 }
2943
2944 // Stop any ringback that might be playing on the channel.
2945 // It's possible the ringback has already stopped, ih which case we'll just
2946 // use the opportunity to remove the channel from ringback_channels_.
2947 if (engine()->voe()->file()) {
2948 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2949 if (it != ringback_channels_.end()) {
2950 if (engine()->voe()->file()->IsPlayingFileLocally(
2951 which_channel) == 1) {
2952 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2953 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2954 << " due to incoming media";
2955 }
2956 ringback_channels_.erase(which_channel);
2957 }
2958 }
2959
2960 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002961 engine()->voe()->network()->ReceivedRTPPacket(
2962 which_channel,
2963 packet->data(),
2964 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965}
2966
wu@webrtc.orga9890802013-12-13 00:21:03 +00002967void WebRtcVoiceMediaChannel::OnRtcpReceived(
2968 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002969 // Sending channels need all RTCP packets with feedback information.
2970 // Even sender reports can contain attached report blocks.
2971 // Receiving channels need sender reports in order to create
2972 // correct receiver reports.
2973 int type = 0;
2974 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2975 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2976 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977 }
2978
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002979 // If it is a sender report, find the channel that is listening.
2980 bool has_sent_to_default_channel = false;
2981 if (type == kRtcpTypeSR) {
2982 int which_channel = GetReceiveChannelNum(
2983 ParseSsrc(packet->data(), packet->length(), true));
2984 if (which_channel != -1) {
2985 engine()->voe()->network()->ReceivedRTCPPacket(
2986 which_channel,
2987 packet->data(),
2988 static_cast<unsigned int>(packet->length()));
2989
2990 if (IsDefaultChannel(which_channel))
2991 has_sent_to_default_channel = true;
2992 }
2993 }
2994
2995 // SR may continue RR and any RR entry may correspond to any one of the send
2996 // channels. So all RTCP packets must be forwarded all send channels. VoE
2997 // will filter out RR internally.
2998 for (ChannelMap::iterator iter = send_channels_.begin();
2999 iter != send_channels_.end(); ++iter) {
3000 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003001 if (IsDefaultChannel(iter->second->channel()) &&
3002 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003003 continue;
3004
3005 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003006 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003007 packet->data(),
3008 static_cast<unsigned int>(packet->length()));
3009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003010}
3011
3012bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003013 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3014 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003015 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3016 return false;
3017 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003018 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3019 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003020 return false;
3021 }
3022 return true;
3023}
3024
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003025bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3026 // TODO(andresp): Add support for setting an independent start bandwidth when
3027 // bandwidth estimation is enabled for voice engine.
3028 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003029}
3030
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003031bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3032 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3033
3034 return SetSendBandwidthInternal(bps);
3035}
3036
3037bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3038 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3039
3040 send_bw_setting_ = true;
3041 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003042
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003044 LOG(LS_INFO) << "The send codec has not been set up yet. "
3045 << "The send bandwidth setting will be applied later.";
3046 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003047 }
3048
3049 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003050 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3051 // SetMaxSendBandwith(0), the second call removes the previous limit.
3052 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053 return true;
3054
3055 webrtc::CodecInst codec = *send_codec_;
3056 bool is_multi_rate = IsCodecMultiRate(codec);
3057
3058 if (is_multi_rate) {
3059 // If codec is multi-rate then just set the bitrate.
3060 codec.rate = bps;
3061 if (!SetSendCodec(codec)) {
3062 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3063 << " to bitrate " << bps << " bps.";
3064 return false;
3065 }
3066 return true;
3067 } else {
3068 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3069 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3070 // fixed bitrate then ignore.
3071 if (bps < codec.rate) {
3072 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3073 << " to bitrate " << bps << " bps"
3074 << ", requires at least " << codec.rate << " bps.";
3075 return false;
3076 }
3077 return true;
3078 }
3079}
3080
3081bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003082 bool echo_metrics_on = false;
3083 // These can take on valid negative values, so use the lowest possible level
3084 // as default rather than -1.
3085 int echo_return_loss = -100;
3086 int echo_return_loss_enhancement = -100;
3087 // These can also be negative, but in practice -1 is only used to signal
3088 // insufficient data, since the resolution is limited to multiples of 4 ms.
3089 int echo_delay_median_ms = -1;
3090 int echo_delay_std_ms = -1;
3091 if (engine()->voe()->processing()->GetEcMetricsStatus(
3092 echo_metrics_on) != -1 && echo_metrics_on) {
3093 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3094 // here, but it appears to be unsuitable currently. Revisit after this is
3095 // investigated: http://b/issue?id=5666755
3096 int erl, erle, rerl, anlp;
3097 if (engine()->voe()->processing()->GetEchoMetrics(
3098 erl, erle, rerl, anlp) != -1) {
3099 echo_return_loss = erl;
3100 echo_return_loss_enhancement = erle;
3101 }
3102
3103 int median, std;
3104 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3105 echo_delay_median_ms = median;
3106 echo_delay_std_ms = std;
3107 }
3108 }
3109
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110 webrtc::CallStatistics cs;
3111 unsigned int ssrc;
3112 webrtc::CodecInst codec;
3113 unsigned int level;
3114
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003115 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3116 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003117 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003118
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003119 // Fill in the sender info, based on what we know, and what the
3120 // remote side told us it got from its RTCP report.
3121 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003122
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003123 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3124 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3125 continue;
3126 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003127
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003128 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003129 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3130 sinfo.bytes_sent = cs.bytesSent;
3131 sinfo.packets_sent = cs.packetsSent;
3132 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3133 // returns 0 to indicate an error value.
3134 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3135
3136 // Get data from the last remote RTCP report. Use default values if no data
3137 // available.
3138 sinfo.fraction_lost = -1.0;
3139 sinfo.jitter_ms = -1;
3140 sinfo.packets_lost = -1;
3141 sinfo.ext_seqnum = -1;
3142 std::vector<webrtc::ReportBlock> receive_blocks;
3143 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3144 channel, &receive_blocks) != -1 &&
3145 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3146 std::vector<webrtc::ReportBlock>::iterator iter;
3147 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3148 ++iter) {
3149 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003150 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003151 // Convert Q8 to floating point.
3152 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3153 // Convert samples to milliseconds.
3154 if (codec.plfreq / 1000 > 0) {
3155 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3156 }
3157 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3158 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3159 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161 }
3162 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003163
3164 // Local speech level.
3165 sinfo.audio_level = (engine()->voe()->volume()->
3166 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3167
3168 // TODO(xians): We are injecting the same APM logging to all the send
3169 // channels here because there is no good way to know which send channel
3170 // is using the APM. The correct fix is to allow the send channels to have
3171 // their own APM so that we can feed the correct APM logging to different
3172 // send channels. See issue crbug/264611 .
3173 sinfo.echo_return_loss = echo_return_loss;
3174 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3175 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3176 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003177 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3178 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003179 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003180
3181 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182 }
3183
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003184 // Build the list of receivers, one for each receiving channel, or 1 in
3185 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003187 for (ChannelMap::const_iterator it = receive_channels_.begin();
3188 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003189 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 }
3191 if (channels.empty()) {
3192 channels.push_back(voe_channel());
3193 }
3194
3195 // Get the SSRC and stats for each receiver, based on our own calculations.
3196 for (std::vector<int>::const_iterator it = channels.begin();
3197 it != channels.end(); ++it) {
3198 memset(&cs, 0, sizeof(cs));
3199 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3200 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3201 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3202 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003203 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003204 rinfo.bytes_rcvd = cs.bytesReceived;
3205 rinfo.packets_rcvd = cs.packetsReceived;
3206 // The next four fields are from the most recently sent RTCP report.
3207 // Convert Q8 to floating point.
3208 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3209 rinfo.packets_lost = cs.cumulativeLost;
3210 rinfo.ext_seqnum = cs.extendedMax;
3211 // Convert samples to milliseconds.
3212 if (codec.plfreq / 1000 > 0) {
3213 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3214 }
3215
3216 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3217 webrtc::NetworkStatistics ns;
3218 if (engine()->voe()->neteq() &&
3219 engine()->voe()->neteq()->GetNetworkStatistics(
3220 *it, ns) != -1) {
3221 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3222 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3223 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003224 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003226
3227 webrtc::AudioDecodingCallStats ds;
3228 if (engine()->voe()->neteq() &&
3229 engine()->voe()->neteq()->GetDecodingCallStatistics(
3230 *it, &ds) != -1) {
3231 rinfo.decoding_calls_to_silence_generator =
3232 ds.calls_to_silence_generator;
3233 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3234 rinfo.decoding_normal = ds.decoded_normal;
3235 rinfo.decoding_plc = ds.decoded_plc;
3236 rinfo.decoding_cng = ds.decoded_cng;
3237 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3238 }
3239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003241 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242 int playout_buffer_delay_ms = 0;
3243 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003244 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3245 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3246 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003247 }
3248
3249 // Get speech level.
3250 rinfo.audio_level = (engine()->voe()->volume()->
3251 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3252 info->receivers.push_back(rinfo);
3253 }
3254 }
3255
3256 return true;
3257}
3258
3259void WebRtcVoiceMediaChannel::GetLastMediaError(
3260 uint32* ssrc, VoiceMediaChannel::Error* error) {
3261 ASSERT(ssrc != NULL);
3262 ASSERT(error != NULL);
3263 FindSsrc(voe_channel(), ssrc);
3264 *error = WebRtcErrorToChannelError(GetLastEngineError());
3265}
3266
3267bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003268 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003270 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3272 // This means the error is not limited to a specific channel. Signal the
3273 // message using ssrc=0. If the current channel is sending, use this
3274 // channel for sending the message.
3275 *ssrc = 0;
3276 return true;
3277 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003278 // Check whether this is a sending channel.
3279 for (ChannelMap::const_iterator it = send_channels_.begin();
3280 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003281 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003282 // This is a sending channel.
3283 uint32 local_ssrc = 0;
3284 if (engine()->voe()->rtp()->GetLocalSSRC(
3285 channel_num, local_ssrc) != -1) {
3286 *ssrc = local_ssrc;
3287 }
3288 return true;
3289 }
3290 }
3291
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003293 for (ChannelMap::const_iterator it = receive_channels_.begin();
3294 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003295 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296 *ssrc = it->first;
3297 return true;
3298 }
3299 }
3300 }
3301 return false;
3302}
3303
3304void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003305 if (error == VE_TYPING_NOISE_WARNING) {
3306 typing_noise_detected_ = true;
3307 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3308 typing_noise_detected_ = false;
3309 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3311}
3312
3313int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3314 unsigned int ulevel;
3315 int ret =
3316 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3317 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3318}
3319
3320int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003321 ChannelMap::iterator it = receive_channels_.find(ssrc);
3322 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003323 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3325}
3326
3327int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003328 ChannelMap::iterator it = send_channels_.find(ssrc);
3329 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003330 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003331
3332 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003333}
3334
3335bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3336 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3337 // Get the RED encodings from the parameter with no name. This may
3338 // change based on what is discussed on the Jingle list.
3339 // The encoding parameter is of the form "a/b"; we only support where
3340 // a == b. Verify this and parse out the value into red_pt.
3341 // If the parameter value is absent (as it will be until we wire up the
3342 // signaling of this message), use the second codec specified (i.e. the
3343 // one after "red") as the encoding parameter.
3344 int red_pt = -1;
3345 std::string red_params;
3346 CodecParameterMap::const_iterator it = red_codec.params.find("");
3347 if (it != red_codec.params.end()) {
3348 red_params = it->second;
3349 std::vector<std::string> red_pts;
3350 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3351 red_pts[0] != red_pts[1] ||
3352 !talk_base::FromString(red_pts[0], &red_pt)) {
3353 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3354 return false;
3355 }
3356 } else if (red_codec.params.empty()) {
3357 LOG(LS_WARNING) << "RED params not present, using defaults";
3358 if (all_codecs.size() > 1) {
3359 red_pt = all_codecs[1].id;
3360 }
3361 }
3362
3363 // Try to find red_pt in |codecs|.
3364 std::vector<AudioCodec>::const_iterator codec;
3365 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3366 if (codec->id == red_pt)
3367 break;
3368 }
3369
3370 // If we find the right codec, that will be the codec we pass to
3371 // SetSendCodec, with the desired payload type.
3372 if (codec != all_codecs.end() &&
3373 engine()->FindWebRtcCodec(*codec, send_codec)) {
3374 } else {
3375 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3376 return false;
3377 }
3378
3379 return true;
3380}
3381
3382bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3383 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003384 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003385 return false;
3386 }
3387 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3388 // what we want to do with them.
3389 // engine()->voe().EnableVQMon(voe_channel(), true);
3390 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3391 return true;
3392}
3393
3394bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3395 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3396 for (int i = 0; i < ncodecs; ++i) {
3397 webrtc::CodecInst voe_codec;
3398 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3399 voe_codec.pltype = -1;
3400 if (engine()->voe()->codec()->SetRecPayloadType(
3401 channel, voe_codec) == -1) {
3402 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3403 return false;
3404 }
3405 }
3406 }
3407 return true;
3408}
3409
3410bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3411 if (playout) {
3412 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3413 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3414 LOG_RTCERR1(StartPlayout, channel);
3415 return false;
3416 }
3417 } else {
3418 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3419 engine()->voe()->base()->StopPlayout(channel);
3420 }
3421 return true;
3422}
3423
3424uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3425 bool rtcp) {
3426 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3427 uint32 ssrc = 0;
3428 if (len >= (ssrc_pos + sizeof(ssrc))) {
3429 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3430 }
3431 return ssrc;
3432}
3433
3434// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3435VoiceMediaChannel::Error
3436 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3437 switch (err_code) {
3438 case 0:
3439 return ERROR_NONE;
3440 case VE_CANNOT_START_RECORDING:
3441 case VE_MIC_VOL_ERROR:
3442 case VE_GET_MIC_VOL_ERROR:
3443 case VE_CANNOT_ACCESS_MIC_VOL:
3444 return ERROR_REC_DEVICE_OPEN_FAILED;
3445 case VE_SATURATION_WARNING:
3446 return ERROR_REC_DEVICE_SATURATION;
3447 case VE_REC_DEVICE_REMOVED:
3448 return ERROR_REC_DEVICE_REMOVED;
3449 case VE_RUNTIME_REC_WARNING:
3450 case VE_RUNTIME_REC_ERROR:
3451 return ERROR_REC_RUNTIME_ERROR;
3452 case VE_CANNOT_START_PLAYOUT:
3453 case VE_SPEAKER_VOL_ERROR:
3454 case VE_GET_SPEAKER_VOL_ERROR:
3455 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3456 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3457 case VE_RUNTIME_PLAY_WARNING:
3458 case VE_RUNTIME_PLAY_ERROR:
3459 return ERROR_PLAY_RUNTIME_ERROR;
3460 case VE_TYPING_NOISE_WARNING:
3461 return ERROR_REC_TYPING_NOISE_DETECTED;
3462 default:
3463 return VoiceMediaChannel::ERROR_OTHER;
3464 }
3465}
3466
3467int WebRtcSoundclipStream::Read(void *buf, int len) {
3468 size_t res = 0;
3469 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003470 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003471}
3472
3473int WebRtcSoundclipStream::Rewind() {
3474 mem_.Rewind();
3475 // Return -1 to keep VoiceEngine from looping.
3476 return (loop_) ? 0 : -1;
3477}
3478
3479} // namespace cricket
3480
3481#endif // HAVE_WEBRTC_VOICE