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