blob: 4ad2ff502c3ba45b73a0d68435e6b44dbd019b5c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
41#include "talk/base/base64.h"
42#include "talk/base/byteorder.h"
43#include "talk/base/common.h"
44#include "talk/base/helpers.h"
45#include "talk/base/logging.h"
46#include "talk/base/stringencode.h"
47#include "talk/base/stringutils.h"
48#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
110// extension header for audio levels, as defined in
111// http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03
112static const char kRtpAudioLevelHeaderExtension[] =
113 "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
114static const int kRtpAudioLevelHeaderExtensionId = 1;
115
116static const char kIsacCodecName[] = "ISAC";
117static const char kL16CodecName[] = "L16";
118// Codec parameters for Opus.
119static const int kOpusMonoBitrate = 32000;
120// Parameter used for NACK.
121// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
122static const int kNackMaxPackets = 250;
123static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000124// draft-spittka-payload-rtp-opus-03
125// Opus bitrate should be in the range between 6000 and 510000.
126static const int kOpusMinBitrate = 6000;
127static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000128// Default audio dscp value.
129// See http://tools.ietf.org/html/rfc2474 for details.
130// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
131static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000133// Ensure we open the file in a writeable path on ChromeOS and Android. This
134// workaround can be removed when it's possible to specify a filename for audio
135// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000136//
137// TODO(grunell): Use a string in the options instead of hardcoding it here
138// and let the embedder choose the filename (crbug.com/264223).
139//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
141// below.
142#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144#elif defined(ANDROID)
145static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000146#else
147static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
148#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Dumps an AudioCodec in RFC 2327-ish format.
151static std::string ToString(const AudioCodec& codec) {
152 std::stringstream ss;
153 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154 << " (" << codec.id << ")";
155 return ss.str();
156}
157static std::string ToString(const webrtc::CodecInst& codec) {
158 std::stringstream ss;
159 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160 << " (" << codec.pltype << ")";
161 return ss.str();
162}
163
164static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
165 const char* delim = "\r\n";
166 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
167 LOG_V(sev) << tok;
168 }
169}
170
171// Severity is an integer because it comes is assumed to be from command line.
172static int SeverityToFilter(int severity) {
173 int filter = webrtc::kTraceNone;
174 switch (severity) {
175 case talk_base::LS_VERBOSE:
176 filter |= webrtc::kTraceAll;
177 case talk_base::LS_INFO:
178 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
179 case talk_base::LS_WARNING:
180 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
181 case talk_base::LS_ERROR:
182 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
183 }
184 return filter;
185}
186
187static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190 kCodecPrefs[i].clockrate == codec.plfreq) {
191 return kCodecPrefs[i].is_multi_rate;
192 }
193 }
194 return false;
195}
196
197static bool FindCodec(const std::vector<AudioCodec>& codecs,
198 const AudioCodec& codec,
199 AudioCodec* found_codec) {
200 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
201 it != codecs.end(); ++it) {
202 if (it->Matches(codec)) {
203 if (found_codec != NULL) {
204 *found_codec = *it;
205 }
206 return true;
207 }
208 }
209 return false;
210}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000211
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212static bool IsNackEnabled(const AudioCodec& codec) {
213 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
214 kParamValueEmpty));
215}
216
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217// Gets the default set of options applied to the engine. Historically, these
218// were supplied as a combination of flags from the channel manager (ec, agc,
219// ns, and highpass) and the rest hardcoded in InitInternal.
220static AudioOptions GetDefaultEngineOptions() {
221 AudioOptions options;
222 options.echo_cancellation.Set(true);
223 options.auto_gain_control.Set(true);
224 options.noise_suppression.Set(true);
225 options.highpass_filter.Set(true);
226 options.stereo_swapping.Set(false);
227 options.typing_detection.Set(true);
228 options.conference_mode.Set(false);
229 options.adjust_agc_delta.Set(0);
230 options.experimental_agc.Set(false);
231 options.experimental_aec.Set(false);
232 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000233 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000234 return options;
235}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236
237class WebRtcSoundclipMedia : public SoundclipMedia {
238 public:
239 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
240 : engine_(engine), webrtc_channel_(-1) {
241 engine_->RegisterSoundclip(this);
242 }
243
244 virtual ~WebRtcSoundclipMedia() {
245 engine_->UnregisterSoundclip(this);
246 if (webrtc_channel_ != -1) {
247 // We shouldn't have to call Disable() here. DeleteChannel() should call
248 // StopPlayout() while deleting the channel. We should fix the bug
249 // inside WebRTC and remove the Disable() call bellow. This work is
250 // tracked by bug http://b/issue?id=5382855.
251 PlaySound(NULL, 0, 0);
252 Disable();
253 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
254 == -1) {
255 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
256 }
257 }
258 }
259
260 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000261 if (!engine_->voe_sc()) {
262 return false;
263 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000264 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000265 if (webrtc_channel_ == -1) {
266 LOG_RTCERR0(CreateChannel);
267 return false;
268 }
269 return true;
270 }
271
272 bool Enable() {
273 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
274 LOG_RTCERR1(StartPlayout, webrtc_channel_);
275 return false;
276 }
277 return true;
278 }
279
280 bool Disable() {
281 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
282 LOG_RTCERR1(StopPlayout, webrtc_channel_);
283 return false;
284 }
285 return true;
286 }
287
288 virtual bool PlaySound(const char *buf, int len, int flags) {
289 // The voe file api is not available in chrome.
290 if (!engine_->voe_sc()->file()) {
291 return false;
292 }
293 // Must stop playing the current sound (if any), because we are about to
294 // modify the stream.
295 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
296 == -1) {
297 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
298 return false;
299 }
300
301 if (buf) {
302 stream_.reset(new WebRtcSoundclipStream(buf, len));
303 stream_->set_loop((flags & SF_LOOP) != 0);
304 stream_->Rewind();
305
306 // Play it.
307 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
308 webrtc_channel_, stream_.get()) == -1) {
309 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
310 LOG(LS_ERROR) << "Unable to start soundclip";
311 return false;
312 }
313 } else {
314 stream_.reset();
315 }
316 return true;
317 }
318
319 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
320
321 private:
322 WebRtcVoiceEngine *engine_;
323 int webrtc_channel_;
324 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
325};
326
327WebRtcVoiceEngine::WebRtcVoiceEngine()
328 : voe_wrapper_(new VoEWrapper()),
329 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000330 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 tracing_(new VoETraceWrapper()),
332 adm_(NULL),
333 adm_sc_(NULL),
334 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
335 is_dumping_aec_(false),
336 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000337 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338 tx_processor_ssrc_(0),
339 rx_processor_ssrc_(0) {
340 Construct();
341}
342
343WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
344 VoEWrapper* voe_wrapper_sc,
345 VoETraceWrapper* tracing)
346 : voe_wrapper_(voe_wrapper),
347 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000348 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000349 tracing_(tracing),
350 adm_(NULL),
351 adm_sc_(NULL),
352 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
353 is_dumping_aec_(false),
354 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000355 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 tx_processor_ssrc_(0),
357 rx_processor_ssrc_(0) {
358 Construct();
359}
360
361void WebRtcVoiceEngine::Construct() {
362 SetTraceFilter(log_filter_);
363 initialized_ = false;
364 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
365 SetTraceOptions("");
366 if (tracing_->SetTraceCallback(this) == -1) {
367 LOG_RTCERR0(SetTraceCallback);
368 }
369 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
370 LOG_RTCERR0(RegisterVoiceEngineObserver);
371 }
372 // Clear the default agc state.
373 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
374
375 // Load our audio codec list.
376 ConstructCodecs();
377
378 // Load our RTP Header extensions.
379 rtp_header_extensions_.push_back(
380 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
381 kRtpAudioLevelHeaderExtensionId));
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000382 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000383
384 // Initialize the VoE Configuration to the default ACM.
385 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
386 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387}
388
389static bool IsOpus(const AudioCodec& codec) {
390 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
391}
392
393static bool IsIsac(const AudioCodec& codec) {
394 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
395}
396
397// True if params["stereo"] == "1"
398static bool IsOpusStereoEnabled(const AudioCodec& codec) {
399 CodecParameterMap::const_iterator param =
400 codec.params.find(kCodecParamStereo);
401 if (param == codec.params.end()) {
402 return false;
403 }
404 return param->second == kParamValueTrue;
405}
406
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000407static bool IsValidOpusBitrate(int bitrate) {
408 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
409}
410
411// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
412// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
413static int GetOpusBitrateFromParams(const AudioCodec& codec) {
414 int bitrate = 0;
415 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
416 return 0;
417 }
418 if (!IsValidOpusBitrate(bitrate)) {
419 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
420 << "invalid value: " << bitrate;
421 return 0;
422 }
423 return bitrate;
424}
425
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000426void WebRtcVoiceEngine::ConstructCodecs() {
427 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
428 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
429 for (int i = 0; i < ncodecs; ++i) {
430 webrtc::CodecInst voe_codec;
431 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
432 // Skip uncompressed formats.
433 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
434 continue;
435 }
436
437 const CodecPref* pref = NULL;
438 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
439 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
440 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
441 kCodecPrefs[j].channels == voe_codec.channels) {
442 pref = &kCodecPrefs[j];
443 break;
444 }
445 }
446
447 if (pref) {
448 // Use the payload type that we've configured in our pref table;
449 // use the offset in our pref table to determine the sort order.
450 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
451 voe_codec.rate, voe_codec.channels,
452 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
453 LOG(LS_INFO) << ToString(codec);
454 if (IsIsac(codec)) {
455 // Indicate auto-bandwidth in signaling.
456 codec.bitrate = 0;
457 }
458 if (IsOpus(codec)) {
459 // Only add fmtp parameters that differ from the spec.
460 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
461 codec.params[kCodecParamMinPTime] =
462 talk_base::ToString(kPreferredMinPTime);
463 }
464 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
465 codec.params[kCodecParamMaxPTime] =
466 talk_base::ToString(kPreferredMaxPTime);
467 }
468 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
469 // when they can be set to values other than the default.
470 }
471 codecs_.push_back(codec);
472 } else {
473 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
474 }
475 }
476 }
477 // Make sure they are in local preference order.
478 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
479}
480
481WebRtcVoiceEngine::~WebRtcVoiceEngine() {
482 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
483 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
484 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
485 }
486 if (adm_) {
487 voe_wrapper_.reset();
488 adm_->Release();
489 adm_ = NULL;
490 }
491 if (adm_sc_) {
492 voe_wrapper_sc_.reset();
493 adm_sc_->Release();
494 adm_sc_ = NULL;
495 }
496
497 // Test to see if the media processor was deregistered properly
498 ASSERT(SignalRxMediaFrame.is_empty());
499 ASSERT(SignalTxMediaFrame.is_empty());
500
501 tracing_->SetTraceCallback(NULL);
502}
503
504bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
505 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
506 bool res = InitInternal();
507 if (res) {
508 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
509 } else {
510 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
511 Terminate();
512 }
513 return res;
514}
515
516bool WebRtcVoiceEngine::InitInternal() {
517 // Temporarily turn logging level up for the Init call
518 int old_filter = log_filter_;
519 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
520 SetTraceFilter(extended_filter);
521 SetTraceOptions("");
522
523 // Init WebRtc VoiceEngine.
524 if (voe_wrapper_->base()->Init(adm_) == -1) {
525 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
526 SetTraceFilter(old_filter);
527 return false;
528 }
529
530 SetTraceFilter(old_filter);
531 SetTraceOptions(log_options_);
532
533 // Log the VoiceEngine version info
534 char buffer[1024] = "";
535 voe_wrapper_->base()->GetVersion(buffer);
536 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
537 LogMultiline(talk_base::LS_INFO, buffer);
538
539 // Save the default AGC configuration settings. This must happen before
540 // calling SetOptions or the default will be overwritten.
541 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000542 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543 return false;
544 }
545
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000546 // Set defaults for options, so that ApplyOptions applies them explicitly
547 // when we clear option (channel) overrides. External clients can still
548 // modify the defaults via SetOptions (on the media engine).
549 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000550 return false;
551 }
552
553 // Print our codec list again for the call diagnostic log
554 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
555 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
556 it != codecs_.end(); ++it) {
557 LOG(LS_INFO) << ToString(*it);
558 }
559
wu@webrtc.org4551b792013-10-09 15:37:36 +0000560 // Disable the DTMF playout when a tone is sent.
561 // PlayDtmfTone will be used if local playout is needed.
562 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
563 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
564 }
565
566 initialized_ = true;
567 return true;
568}
569
570bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
571 if (voe_wrapper_sc_initialized_) {
572 return true;
573 }
574 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
575 // be false, so subsequent calls to EnsureSoundclipEngineInit will
576 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577#if defined(LINUX) && !defined(HAVE_LIBPULSE)
578 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
579#endif
580
581 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
582 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
583 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
584 return false;
585 }
586
587 // On Windows, tell it to use the default sound (not communication) devices.
588 // First check whether there is a valid sound device for playback.
589 // TODO(juberti): Clean this up when we support setting the soundclip device.
590#ifdef WIN32
591 // The SetPlayoutDevice may not be implemented in the case of external ADM.
592 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
593 // PeerConnection interface never set the adm_sc_, so need to check both
594 // in order to determine if the external adm is used.
595 if (!adm_ && !adm_sc_) {
596 int num_of_devices = 0;
597 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
598 num_of_devices > 0) {
599 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
600 == -1) {
601 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
602 voe_wrapper_sc_->error());
603 return false;
604 }
605 } else {
606 LOG(LS_WARNING) << "No valid sound playout device found.";
607 }
608 }
609#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000610 voe_wrapper_sc_initialized_ = true;
611 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 return true;
613}
614
615void WebRtcVoiceEngine::Terminate() {
616 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
617 initialized_ = false;
618
619 StopAecDump();
620
wu@webrtc.org4551b792013-10-09 15:37:36 +0000621 if (voe_wrapper_sc_) {
622 voe_wrapper_sc_initialized_ = false;
623 voe_wrapper_sc_->base()->Terminate();
624 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625 voe_wrapper_->base()->Terminate();
626 desired_local_monitor_enable_ = false;
627}
628
629int WebRtcVoiceEngine::GetCapabilities() {
630 return AUDIO_SEND | AUDIO_RECV;
631}
632
633VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
634 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
635 if (!ch->valid()) {
636 delete ch;
637 ch = NULL;
638 }
639 return ch;
640}
641
642SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000643 if (!EnsureSoundclipEngineInit()) {
644 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
645 << "initialize.";
646 return NULL;
647 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000648 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
649 if (!soundclip->Init() || !soundclip->Enable()) {
650 delete soundclip;
651 return NULL;
652 }
653 return soundclip;
654}
655
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000656bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 if (!ApplyOptions(options)) {
658 return false;
659 }
660 options_ = options;
661 return true;
662}
663
664bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
665 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
666 if (!ApplyOptions(overrides)) {
667 return false;
668 }
669 option_overrides_ = overrides;
670 return true;
671}
672
673bool WebRtcVoiceEngine::ClearOptionOverrides() {
674 LOG(LS_INFO) << "Clearing option overrides.";
675 AudioOptions options = options_;
676 // Only call ApplyOptions if |options_overrides_| contains overrided options.
677 // ApplyOptions affects NS, AGC other options that is shared between
678 // all WebRtcVoiceEngineChannels.
679 if (option_overrides_ == AudioOptions()) {
680 return true;
681 }
682
683 if (!ApplyOptions(options)) {
684 return false;
685 }
686 option_overrides_ = AudioOptions();
687 return true;
688}
689
690// AudioOptions defaults are set in InitInternal (for options with corresponding
691// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
692bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
693 AudioOptions options = options_in; // The options are modified below.
694 // kEcConference is AEC with high suppression.
695 webrtc::EcModes ec_mode = webrtc::kEcConference;
696 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
697 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
698 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
699 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000700 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
701 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
702 << aecm_comfort_noise << " (default is false).";
703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704
705#if defined(IOS)
706 // On iOS, VPIO provides built-in EC and AGC.
707 options.echo_cancellation.Set(false);
708 options.auto_gain_control.Set(false);
709#elif defined(ANDROID)
710 ec_mode = webrtc::kEcAecm;
711#endif
712
713#if defined(IOS) || defined(ANDROID)
714 // Set the AGC mode for iOS as well despite disabling it above, to avoid
715 // unsupported configuration errors from webrtc.
716 agc_mode = webrtc::kAgcFixedDigital;
717 options.typing_detection.Set(false);
718 options.experimental_agc.Set(false);
719 options.experimental_aec.Set(false);
720#endif
721
722 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
723
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000724 // Configure whether ACM1 or ACM2 is used.
725 bool enable_acm2 = false;
726 if (options.experimental_acm.Get(&enable_acm2)) {
727 EnableExperimentalAcm(enable_acm2);
728 }
729
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
731
732 bool echo_cancellation;
733 if (options.echo_cancellation.Get(&echo_cancellation)) {
734 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
735 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
736 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000737 } else {
738 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
739 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 }
741#if !defined(ANDROID)
742 // TODO(ajm): Remove the error return on Android from webrtc.
743 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
744 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
745 return false;
746 }
747#endif
748 if (ec_mode == webrtc::kEcAecm) {
749 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
750 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
751 return false;
752 }
753 }
754 }
755
756 bool auto_gain_control;
757 if (options.auto_gain_control.Get(&auto_gain_control)) {
758 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
759 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
760 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000761 } else {
762 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
763 << " with mode " << agc_mode;
764 }
765 }
766
767 if (options.tx_agc_target_dbov.IsSet() ||
768 options.tx_agc_digital_compression_gain.IsSet() ||
769 options.tx_agc_limiter.IsSet()) {
770 // Override default_agc_config_. Generally, an unset option means "leave
771 // the VoE bits alone" in this function, so we want whatever is set to be
772 // stored as the new "default". If we didn't, then setting e.g.
773 // tx_agc_target_dbov would reset digital compression gain and limiter
774 // settings.
775 // Also, if we don't update default_agc_config_, then adjust_agc_delta
776 // would be an offset from the original values, and not whatever was set
777 // explicitly.
778 default_agc_config_.targetLeveldBOv =
779 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
780 default_agc_config_.targetLeveldBOv);
781 default_agc_config_.digitalCompressionGaindB =
782 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
783 default_agc_config_.digitalCompressionGaindB);
784 default_agc_config_.limiterEnable =
785 options.tx_agc_limiter.GetWithDefaultIfUnset(
786 default_agc_config_.limiterEnable);
787 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
788 LOG_RTCERR3(SetAgcConfig,
789 default_agc_config_.targetLeveldBOv,
790 default_agc_config_.digitalCompressionGaindB,
791 default_agc_config_.limiterEnable);
792 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 }
794 }
795
796 bool noise_suppression;
797 if (options.noise_suppression.Get(&noise_suppression)) {
798 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
799 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
800 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000801 } else {
802 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
803 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 }
805 }
806
807 bool highpass_filter;
808 if (options.highpass_filter.Get(&highpass_filter)) {
809 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
810 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
811 return false;
812 }
813 }
814
815 bool stereo_swapping;
816 if (options.stereo_swapping.Get(&stereo_swapping)) {
817 voep->EnableStereoChannelSwapping(stereo_swapping);
818 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
819 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
820 return false;
821 }
822 }
823
824 bool typing_detection;
825 if (options.typing_detection.Get(&typing_detection)) {
826 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
827 // In case of error, log the info and continue
828 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
829 }
830 }
831
832 int adjust_agc_delta;
833 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
834 if (!AdjustAgcLevel(adjust_agc_delta)) {
835 return false;
836 }
837 }
838
839 bool aec_dump;
840 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000842 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 else
844 StopAecDump();
845 }
846
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000847 bool experimental_aec;
848 if (options.experimental_aec.Get(&experimental_aec)) {
849 webrtc::AudioProcessing* audioproc =
850 voe_wrapper_->base()->audio_processing();
851 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
852 // returns NULL on audio_processing().
853 if (audioproc) {
854 webrtc::Config config;
855 config.Set<webrtc::DelayCorrection>(
856 new webrtc::DelayCorrection(experimental_aec));
857 audioproc->SetExtraOptions(config);
858 }
859 }
860
wu@webrtc.org97077a32013-10-25 21:18:33 +0000861 uint32 recording_sample_rate;
862 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
863 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
864 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
865 }
866 }
867
868 uint32 playout_sample_rate;
869 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
870 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
871 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
872 }
873 }
874
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875
876 return true;
877}
878
879bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
880 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
881 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
882 LOG_RTCERR1(SetDelayOffsetMs, offset);
883 return false;
884 }
885
886 return true;
887}
888
889struct ResumeEntry {
890 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
891 : channel(c),
892 playout(p),
893 send(s) {
894 }
895
896 WebRtcVoiceMediaChannel *channel;
897 bool playout;
898 SendFlags send;
899};
900
901// TODO(juberti): Refactor this so that the core logic can be used to set the
902// soundclip device. At that time, reinstate the soundclip pause/resume code.
903bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
904 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000905#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
907 kDefaultAudioDeviceId;
908 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
909 kDefaultAudioDeviceId;
910 // The device manager uses -1 as the default device, which was the case for
911 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
912#ifndef WIN32
913 if (-1 == in_id) {
914 in_id = kDefaultAudioDeviceId;
915 }
916 if (-1 == out_id) {
917 out_id = kDefaultAudioDeviceId;
918 }
919#endif
920
921 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
922 in_device->name : "Default device";
923 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
924 out_device->name : "Default device";
925 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
926 << ") and speaker to (id=" << out_id << ", name=" << out_name
927 << ")";
928
929 // If we're running the local monitor, we need to stop it first.
930 bool ret = true;
931 if (!PauseLocalMonitor()) {
932 LOG(LS_WARNING) << "Failed to pause local monitor";
933 ret = false;
934 }
935
936 // Must also pause all audio playback and capture.
937 for (ChannelList::const_iterator i = channels_.begin();
938 i != channels_.end(); ++i) {
939 WebRtcVoiceMediaChannel *channel = *i;
940 if (!channel->PausePlayout()) {
941 LOG(LS_WARNING) << "Failed to pause playout";
942 ret = false;
943 }
944 if (!channel->PauseSend()) {
945 LOG(LS_WARNING) << "Failed to pause send";
946 ret = false;
947 }
948 }
949
950 // Find the recording device id in VoiceEngine and set recording device.
951 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
952 ret = false;
953 }
954 if (ret) {
955 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000956 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957 ret = false;
958 }
959 }
960
961 // Find the playout device id in VoiceEngine and set playout device.
962 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
963 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
964 ret = false;
965 }
966 if (ret) {
967 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000968 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 ret = false;
970 }
971 }
972
973 // Resume all audio playback and capture.
974 for (ChannelList::const_iterator i = channels_.begin();
975 i != channels_.end(); ++i) {
976 WebRtcVoiceMediaChannel *channel = *i;
977 if (!channel->ResumePlayout()) {
978 LOG(LS_WARNING) << "Failed to resume playout";
979 ret = false;
980 }
981 if (!channel->ResumeSend()) {
982 LOG(LS_WARNING) << "Failed to resume send";
983 ret = false;
984 }
985 }
986
987 // Resume local monitor.
988 if (!ResumeLocalMonitor()) {
989 LOG(LS_WARNING) << "Failed to resume local monitor";
990 ret = false;
991 }
992
993 if (ret) {
994 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
995 << ") and speaker to (id="<< out_id << " name=" << out_name
996 << ")";
997 }
998
999 return ret;
1000#else
1001 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001002#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003}
1004
1005bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1006 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1007 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001008#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 *rtc_id = dev_id;
1010 return true;
1011#else
1012 // In Windows and Mac, we need to find the VoiceEngine device id by name
1013 // unless the input dev_id is the default device id.
1014 if (kDefaultAudioDeviceId == dev_id) {
1015 *rtc_id = dev_id;
1016 return true;
1017 }
1018
1019 // Get the number of VoiceEngine audio devices.
1020 int count = 0;
1021 if (is_input) {
1022 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1023 LOG_RTCERR0(GetNumOfRecordingDevices);
1024 return false;
1025 }
1026 } else {
1027 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1028 LOG_RTCERR0(GetNumOfPlayoutDevices);
1029 return false;
1030 }
1031 }
1032
1033 for (int i = 0; i < count; ++i) {
1034 char name[128];
1035 char guid[128];
1036 if (is_input) {
1037 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1038 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1039 } else {
1040 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1041 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1042 }
1043
1044 std::string webrtc_name(name);
1045 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1046 *rtc_id = i;
1047 return true;
1048 }
1049 }
1050 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1051 return false;
1052#endif
1053}
1054
1055bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1056 unsigned int ulevel;
1057 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1058 LOG_RTCERR1(GetSpeakerVolume, level);
1059 return false;
1060 }
1061 *level = ulevel;
1062 return true;
1063}
1064
1065bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1066 ASSERT(level >= 0 && level <= 255);
1067 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1068 LOG_RTCERR1(SetSpeakerVolume, level);
1069 return false;
1070 }
1071 return true;
1072}
1073
1074int WebRtcVoiceEngine::GetInputLevel() {
1075 unsigned int ulevel;
1076 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1077 static_cast<int>(ulevel) : -1;
1078}
1079
1080bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1081 desired_local_monitor_enable_ = enable;
1082 return ChangeLocalMonitor(desired_local_monitor_enable_);
1083}
1084
1085bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1086 // The voe file api is not available in chrome.
1087 if (!voe_wrapper_->file()) {
1088 return false;
1089 }
1090 if (enable && !monitor_) {
1091 monitor_.reset(new WebRtcMonitorStream);
1092 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1093 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1094 // Must call Stop() because there are some cases where Start will report
1095 // failure but still change the state, and if we leave VE in the on state
1096 // then it could crash later when trying to invoke methods on our monitor.
1097 voe_wrapper_->file()->StopRecordingMicrophone();
1098 monitor_.reset();
1099 return false;
1100 }
1101 } else if (!enable && monitor_) {
1102 voe_wrapper_->file()->StopRecordingMicrophone();
1103 monitor_.reset();
1104 }
1105 return true;
1106}
1107
1108bool WebRtcVoiceEngine::PauseLocalMonitor() {
1109 return ChangeLocalMonitor(false);
1110}
1111
1112bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1113 return ChangeLocalMonitor(desired_local_monitor_enable_);
1114}
1115
1116const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1117 return codecs_;
1118}
1119
1120bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1121 return FindWebRtcCodec(in, NULL);
1122}
1123
1124// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1125bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1126 webrtc::CodecInst* out) {
1127 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1128 for (int i = 0; i < ncodecs; ++i) {
1129 webrtc::CodecInst voe_codec;
1130 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1131 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1132 voe_codec.rate, voe_codec.channels, 0);
1133 bool multi_rate = IsCodecMultiRate(voe_codec);
1134 // Allow arbitrary rates for ISAC to be specified.
1135 if (multi_rate) {
1136 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1137 codec.bitrate = 0;
1138 }
1139 if (codec.Matches(in)) {
1140 if (out) {
1141 // Fixup the payload type.
1142 voe_codec.pltype = in.id;
1143
1144 // Set bitrate if specified.
1145 if (multi_rate && in.bitrate != 0) {
1146 voe_codec.rate = in.bitrate;
1147 }
1148
1149 // Apply codec-specific settings.
1150 if (IsIsac(codec)) {
1151 // If ISAC and an explicit bitrate is not specified,
1152 // enable auto bandwidth adjustment.
1153 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1154 }
1155 *out = voe_codec;
1156 }
1157 return true;
1158 }
1159 }
1160 }
1161 return false;
1162}
1163const std::vector<RtpHeaderExtension>&
1164WebRtcVoiceEngine::rtp_header_extensions() const {
1165 return rtp_header_extensions_;
1166}
1167
1168void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1169 // if min_sev == -1, we keep the current log level.
1170 if (min_sev >= 0) {
1171 SetTraceFilter(SeverityToFilter(min_sev));
1172 }
1173 log_options_ = filter;
1174 SetTraceOptions(initialized_ ? log_options_ : "");
1175}
1176
1177int WebRtcVoiceEngine::GetLastEngineError() {
1178 return voe_wrapper_->error();
1179}
1180
1181void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1182 log_filter_ = filter;
1183 tracing_->SetTraceFilter(filter);
1184}
1185
1186// We suppport three different logging settings for VoiceEngine:
1187// 1. Observer callback that goes into talk diagnostic logfile.
1188// Use --logfile and --loglevel
1189//
1190// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1191// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1192//
1193// 3. EC log and dump for debugging QualityEngine.
1194// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1195//
1196// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1197// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1198void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1199 // Set encrypted trace file.
1200 std::vector<std::string> opts;
1201 talk_base::tokenize(options, ' ', '"', '"', &opts);
1202 std::vector<std::string>::iterator tracefile =
1203 std::find(opts.begin(), opts.end(), "tracefile");
1204 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1205 // Write encrypted debug output (at same loglevel) to file
1206 // EncryptedTraceFile no longer supported.
1207 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1208 LOG_RTCERR1(SetTraceFile, *tracefile);
1209 }
1210 }
1211
wu@webrtc.org97077a32013-10-25 21:18:33 +00001212 // Allow trace options to override the trace filter. We default
1213 // it to log_filter_ (as a translation of libjingle log levels)
1214 // elsewhere, but this allows clients to explicitly set webrtc
1215 // log levels.
1216 std::vector<std::string>::iterator tracefilter =
1217 std::find(opts.begin(), opts.end(), "tracefilter");
1218 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1219 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1220 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1221 }
1222 }
1223
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224 // Set AEC dump file
1225 std::vector<std::string>::iterator recordEC =
1226 std::find(opts.begin(), opts.end(), "recordEC");
1227 if (recordEC != opts.end()) {
1228 ++recordEC;
1229 if (recordEC != opts.end())
1230 StartAecDump(recordEC->c_str());
1231 else
1232 StopAecDump();
1233 }
1234}
1235
1236// Ignore spammy trace messages, mostly from the stats API when we haven't
1237// gotten RTCP info yet from the remote side.
1238bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1239 static const char* kTracesToIgnore[] = {
1240 "\tfailed to GetReportBlockInformation",
1241 "GetRecCodec() failed to get received codec",
1242 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1243 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1244 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1245 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1246 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1247 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1248 "SenderInfoReceived No received SR",
1249 "StatisticsRTP() no statistics available",
1250 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1251 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1252 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1253 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1254 NULL
1255 };
1256 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1257 if (trace.find(*p) != std::string::npos) {
1258 return true;
1259 }
1260 }
1261 return false;
1262}
1263
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001264void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1265 if (enable == use_experimental_acm_)
1266 return;
1267 if (enable) {
1268 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1269 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1270 new webrtc::NewAudioCodingModuleFactory());
1271 } else {
1272 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1273 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1274 new webrtc::AudioCodingModuleFactory());
1275 }
1276 use_experimental_acm_ = enable;
1277}
1278
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1280 int length) {
1281 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1282 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1283 sev = talk_base::LS_ERROR;
1284 else if (level == webrtc::kTraceWarning)
1285 sev = talk_base::LS_WARNING;
1286 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1287 sev = talk_base::LS_INFO;
1288 else if (level == webrtc::kTraceTerseInfo)
1289 sev = talk_base::LS_INFO;
1290
1291 // Skip past boilerplate prefix text
1292 if (length < 72) {
1293 std::string msg(trace, length);
1294 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1295 LOG_V(sev) << msg;
1296 } else {
1297 std::string msg(trace + 71, length - 72);
1298 if (!ShouldIgnoreTrace(msg)) {
1299 LOG_V(sev) << "webrtc: " << msg;
1300 }
1301 }
1302}
1303
1304void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1305 talk_base::CritScope lock(&channels_cs_);
1306 WebRtcVoiceMediaChannel* channel = NULL;
1307 uint32 ssrc = 0;
1308 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1309 << channel_num << ".";
1310 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1311 ASSERT(channel != NULL);
1312 channel->OnError(ssrc, err_code);
1313 } else {
1314 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1315 << " could not be found in channel list when error reported.";
1316 }
1317}
1318
1319bool WebRtcVoiceEngine::FindChannelAndSsrc(
1320 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1321 ASSERT(channel != NULL && ssrc != NULL);
1322
1323 *channel = NULL;
1324 *ssrc = 0;
1325 // Find corresponding channel and ssrc
1326 for (ChannelList::const_iterator it = channels_.begin();
1327 it != channels_.end(); ++it) {
1328 ASSERT(*it != NULL);
1329 if ((*it)->FindSsrc(channel_num, ssrc)) {
1330 *channel = *it;
1331 return true;
1332 }
1333 }
1334
1335 return false;
1336}
1337
1338// This method will search through the WebRtcVoiceMediaChannels and
1339// obtain the voice engine's channel number.
1340bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1341 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1342 ASSERT(channel_num != NULL);
1343 ASSERT(direction == MPD_RX || direction == MPD_TX);
1344
1345 *channel_num = -1;
1346 // Find corresponding channel for ssrc.
1347 for (ChannelList::const_iterator it = channels_.begin();
1348 it != channels_.end(); ++it) {
1349 ASSERT(*it != NULL);
1350 if (direction & MPD_RX) {
1351 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1352 }
1353 if (*channel_num == -1 && (direction & MPD_TX)) {
1354 *channel_num = (*it)->GetSendChannelNum(ssrc);
1355 }
1356 if (*channel_num != -1) {
1357 return true;
1358 }
1359 }
1360 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1361 return false;
1362}
1363
1364void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1365 talk_base::CritScope lock(&channels_cs_);
1366 channels_.push_back(channel);
1367}
1368
1369void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1370 talk_base::CritScope lock(&channels_cs_);
1371 ChannelList::iterator i = std::find(channels_.begin(),
1372 channels_.end(),
1373 channel);
1374 if (i != channels_.end()) {
1375 channels_.erase(i);
1376 }
1377}
1378
1379void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1380 soundclips_.push_back(soundclip);
1381}
1382
1383void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1384 SoundclipList::iterator i = std::find(soundclips_.begin(),
1385 soundclips_.end(),
1386 soundclip);
1387 if (i != soundclips_.end()) {
1388 soundclips_.erase(i);
1389 }
1390}
1391
1392// Adjusts the default AGC target level by the specified delta.
1393// NB: If we start messing with other config fields, we'll want
1394// to save the current webrtc::AgcConfig as well.
1395bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1396 webrtc::AgcConfig config = default_agc_config_;
1397 config.targetLeveldBOv -= delta;
1398
1399 LOG(LS_INFO) << "Adjusting AGC level from default -"
1400 << default_agc_config_.targetLeveldBOv << "dB to -"
1401 << config.targetLeveldBOv << "dB";
1402
1403 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1404 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1405 return false;
1406 }
1407 return true;
1408}
1409
1410bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1411 webrtc::AudioDeviceModule* adm_sc) {
1412 if (initialized_) {
1413 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1414 return false;
1415 }
1416 if (adm_) {
1417 adm_->Release();
1418 adm_ = NULL;
1419 }
1420 if (adm) {
1421 adm_ = adm;
1422 adm_->AddRef();
1423 }
1424
1425 if (adm_sc_) {
1426 adm_sc_->Release();
1427 adm_sc_ = NULL;
1428 }
1429 if (adm_sc) {
1430 adm_sc_ = adm_sc;
1431 adm_sc_->AddRef();
1432 }
1433 return true;
1434}
1435
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001436bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1437 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1438 if (!aec_dump_file_stream) {
1439 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1440 if (!talk_base::ClosePlatformFile(file))
1441 LOG(LS_WARNING) << "Could not close file.";
1442 return false;
1443 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001444 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001445 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001446 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001447 LOG_RTCERR0(StartDebugRecording);
1448 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001449 return false;
1450 }
1451 is_dumping_aec_ = true;
1452 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001453}
1454
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455bool WebRtcVoiceEngine::RegisterProcessor(
1456 uint32 ssrc,
1457 VoiceProcessor* voice_processor,
1458 MediaProcessorDirection direction) {
1459 bool register_with_webrtc = false;
1460 int channel_id = -1;
1461 bool success = false;
1462 uint32* processor_ssrc = NULL;
1463 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1464 if (voice_processor == NULL || !found_channel) {
1465 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1466 << " foundChannel: " << found_channel;
1467 return false;
1468 }
1469
1470 webrtc::ProcessingTypes processing_type;
1471 {
1472 talk_base::CritScope cs(&signal_media_critical_);
1473 if (direction == MPD_RX) {
1474 processing_type = webrtc::kPlaybackAllChannelsMixed;
1475 if (SignalRxMediaFrame.is_empty()) {
1476 register_with_webrtc = true;
1477 processor_ssrc = &rx_processor_ssrc_;
1478 }
1479 SignalRxMediaFrame.connect(voice_processor,
1480 &VoiceProcessor::OnFrame);
1481 } else {
1482 processing_type = webrtc::kRecordingPerChannel;
1483 if (SignalTxMediaFrame.is_empty()) {
1484 register_with_webrtc = true;
1485 processor_ssrc = &tx_processor_ssrc_;
1486 }
1487 SignalTxMediaFrame.connect(voice_processor,
1488 &VoiceProcessor::OnFrame);
1489 }
1490 }
1491 if (register_with_webrtc) {
1492 // TODO(janahan): when registering consider instantiating a
1493 // a VoeMediaProcess object and not make the engine extend the interface.
1494 if (voe()->media() && voe()->media()->
1495 RegisterExternalMediaProcessing(channel_id,
1496 processing_type,
1497 *this) != -1) {
1498 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1499 << channel_id;
1500 *processor_ssrc = ssrc;
1501 success = true;
1502 } else {
1503 LOG_RTCERR2(RegisterExternalMediaProcessing,
1504 channel_id,
1505 processing_type);
1506 success = false;
1507 }
1508 } else {
1509 // If we don't have to register with the engine, we just needed to
1510 // connect a new processor, set success to true;
1511 success = true;
1512 }
1513 return success;
1514}
1515
1516bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1517 MediaProcessorDirection channel_direction,
1518 uint32 ssrc,
1519 VoiceProcessor* voice_processor,
1520 MediaProcessorDirection processor_direction) {
1521 bool success = true;
1522 FrameSignal* signal;
1523 webrtc::ProcessingTypes processing_type;
1524 uint32* processor_ssrc = NULL;
1525 if (channel_direction == MPD_RX) {
1526 signal = &SignalRxMediaFrame;
1527 processing_type = webrtc::kPlaybackAllChannelsMixed;
1528 processor_ssrc = &rx_processor_ssrc_;
1529 } else {
1530 signal = &SignalTxMediaFrame;
1531 processing_type = webrtc::kRecordingPerChannel;
1532 processor_ssrc = &tx_processor_ssrc_;
1533 }
1534
1535 int deregister_id = -1;
1536 {
1537 talk_base::CritScope cs(&signal_media_critical_);
1538 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1539 signal->disconnect(voice_processor);
1540 int channel_id = -1;
1541 bool found_channel = FindChannelNumFromSsrc(ssrc,
1542 channel_direction,
1543 &channel_id);
1544 if (signal->is_empty() && found_channel) {
1545 deregister_id = channel_id;
1546 }
1547 }
1548 }
1549 if (deregister_id != -1) {
1550 if (voe()->media() &&
1551 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1552 processing_type) != -1) {
1553 *processor_ssrc = 0;
1554 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1555 << deregister_id;
1556 } else {
1557 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1558 deregister_id,
1559 processing_type);
1560 success = false;
1561 }
1562 }
1563 return success;
1564}
1565
1566bool WebRtcVoiceEngine::UnregisterProcessor(
1567 uint32 ssrc,
1568 VoiceProcessor* voice_processor,
1569 MediaProcessorDirection direction) {
1570 bool success = true;
1571 if (voice_processor == NULL) {
1572 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1573 << ssrc;
1574 return false;
1575 }
1576 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1577 success = false;
1578 }
1579 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1580 success = false;
1581 }
1582 return success;
1583}
1584
1585// Implementing method from WebRtc VoEMediaProcess interface
1586// Do not lock mux_channel_cs_ in this callback.
1587void WebRtcVoiceEngine::Process(int channel,
1588 webrtc::ProcessingTypes type,
1589 int16_t audio10ms[],
1590 int length,
1591 int sampling_freq,
1592 bool is_stereo) {
1593 talk_base::CritScope cs(&signal_media_critical_);
1594 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1595 if (type == webrtc::kPlaybackAllChannelsMixed) {
1596 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1597 } else if (type == webrtc::kRecordingPerChannel) {
1598 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1599 } else {
1600 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1601 << " channel: " << channel << " type: " << type
1602 << " tx_ssrc: " << tx_processor_ssrc_
1603 << " rx_ssrc: " << rx_processor_ssrc_;
1604 }
1605}
1606
1607void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1608 if (!is_dumping_aec_) {
1609 // Start dumping AEC when we are not dumping.
1610 if (voe_wrapper_->processing()->StartDebugRecording(
1611 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001612 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001613 } else {
1614 is_dumping_aec_ = true;
1615 }
1616 }
1617}
1618
1619void WebRtcVoiceEngine::StopAecDump() {
1620 if (is_dumping_aec_) {
1621 // Stop dumping AEC when we are dumping.
1622 if (voe_wrapper_->processing()->StopDebugRecording() !=
1623 webrtc::AudioProcessing::kNoError) {
1624 LOG_RTCERR0(StopDebugRecording);
1625 }
1626 is_dumping_aec_ = false;
1627 }
1628}
1629
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001630int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001631 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001632}
1633
1634int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1635 return CreateVoiceChannel(voe_wrapper_.get());
1636}
1637
1638int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1639 return CreateVoiceChannel(voe_wrapper_sc_.get());
1640}
1641
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001642class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1643 : public AudioRenderer::Sink {
1644 public:
1645 WebRtcVoiceChannelRenderer(int ch,
1646 webrtc::AudioTransport* voe_audio_transport)
1647 : channel_(ch),
1648 voe_audio_transport_(voe_audio_transport),
1649 renderer_(NULL) {
1650 }
1651 virtual ~WebRtcVoiceChannelRenderer() {
1652 Stop();
1653 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001654
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001655 // Starts the rendering by setting a sink to the renderer to get data
1656 // callback.
1657 // TODO(xians): Make sure Start() is called only once.
1658 void Start(AudioRenderer* renderer) {
1659 ASSERT(renderer != NULL);
1660 if (renderer_) {
1661 ASSERT(renderer_ == renderer);
1662 return;
1663 }
1664
1665 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1666 // in getUserMedia by default.
1667 renderer->AddChannel(channel_);
1668 renderer->SetSink(this);
1669 renderer_ = renderer;
1670 }
1671
1672 // Stops rendering by setting the sink of the renderer to NULL. No data
1673 // callback will be received after this method.
1674 void Stop() {
1675 if (!renderer_)
1676 return;
1677
1678 renderer_->RemoveChannel(channel_);
1679 renderer_->SetSink(NULL);
1680 renderer_ = NULL;
1681 }
1682
1683 // AudioRenderer::Sink implementation.
1684 virtual void OnData(const void* audio_data,
1685 int bits_per_sample,
1686 int sample_rate,
1687 int number_of_channels,
1688 int number_of_frames) OVERRIDE {
1689 // TODO(xians): Make new interface in AudioTransport to pass the data to
1690 // WebRtc VoE channel.
1691 }
1692
1693 // Accessor to the VoE channel ID.
1694 int channel() const { return channel_; }
1695
1696 private:
1697 const int channel_;
1698 webrtc::AudioTransport* const voe_audio_transport_;
1699
1700 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1701 // PeerConnection will make sure invalidating the pointer before the object
1702 // goes away.
1703 AudioRenderer* renderer_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001704};
1705
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706// WebRtcVoiceMediaChannel
1707WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1708 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1709 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001710 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001711 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001712 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713 options_(),
1714 dtmf_allowed_(false),
1715 desired_playout_(false),
1716 nack_enabled_(false),
1717 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001718 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 desired_send_(SEND_NOTHING),
1720 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 default_receive_ssrc_(0) {
1722 engine->RegisterChannel(this);
1723 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1724 << voe_channel();
1725
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001726 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001727}
1728
1729WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1730 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1731 << voe_channel();
1732
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001733 // Remove any remaining send streams, the default channel will be deleted
1734 // later.
1735 while (!send_channels_.empty())
1736 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001737
1738 // Unregister ourselves from the engine.
1739 engine()->UnregisterChannel(this);
1740 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001741 while (!receive_channels_.empty()) {
1742 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743 }
1744
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001745 // Delete the default channel.
1746 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747}
1748
1749bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1750 LOG(LS_INFO) << "Setting voice channel options: "
1751 << options.ToString();
1752
wu@webrtc.orgde305012013-10-31 15:40:38 +00001753 // Check if DSCP value is changed from previous.
1754 bool dscp_option_changed = (options_.dscp != options.dscp);
1755
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001756 // TODO(xians): Add support to set different options for different send
1757 // streams after we support multiple APMs.
1758
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 // We retain all of the existing options, and apply the given ones
1760 // on top. This means there is no way to "clear" options such that
1761 // they go back to the engine default.
1762 options_.SetAll(options);
1763
1764 if (send_ != SEND_NOTHING) {
1765 if (!engine()->SetOptionOverrides(options_)) {
1766 LOG(LS_WARNING) <<
1767 "Failed to engine SetOptionOverrides during channel SetOptions.";
1768 return false;
1769 }
1770 } else {
1771 // Will be interpreted when appropriate.
1772 }
1773
wu@webrtc.org97077a32013-10-25 21:18:33 +00001774 // Receiver-side auto gain control happens per channel, so set it here from
1775 // options. Note that, like conference mode, setting it on the engine won't
1776 // have the desired effect, since voice channels don't inherit options from
1777 // the media engine when those options are applied per-channel.
1778 bool rx_auto_gain_control;
1779 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1780 if (engine()->voe()->processing()->SetRxAgcStatus(
1781 voe_channel(), rx_auto_gain_control,
1782 webrtc::kAgcFixedDigital) == -1) {
1783 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1784 return false;
1785 } else {
1786 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1787 << " with mode " << webrtc::kAgcFixedDigital;
1788 }
1789 }
1790 if (options.rx_agc_target_dbov.IsSet() ||
1791 options.rx_agc_digital_compression_gain.IsSet() ||
1792 options.rx_agc_limiter.IsSet()) {
1793 webrtc::AgcConfig config;
1794 // If only some of the options are being overridden, get the current
1795 // settings for the channel and bail if they aren't available.
1796 if (!options.rx_agc_target_dbov.IsSet() ||
1797 !options.rx_agc_digital_compression_gain.IsSet() ||
1798 !options.rx_agc_limiter.IsSet()) {
1799 if (engine()->voe()->processing()->GetRxAgcConfig(
1800 voe_channel(), config) != 0) {
1801 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1802 << "channel " << voe_channel() << ". Since not all rx "
1803 << "agc options are specified, unable to safely set rx "
1804 << "agc options.";
1805 return false;
1806 }
1807 }
1808 config.targetLeveldBOv =
1809 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1810 config.targetLeveldBOv);
1811 config.digitalCompressionGaindB =
1812 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1813 config.digitalCompressionGaindB);
1814 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1815 config.limiterEnable);
1816 if (engine()->voe()->processing()->SetRxAgcConfig(
1817 voe_channel(), config) == -1) {
1818 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1819 config.digitalCompressionGaindB, config.limiterEnable);
1820 return false;
1821 }
1822 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001823 if (dscp_option_changed) {
1824 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001825 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001826 dscp = kAudioDscpValue;
1827 if (MediaChannel::SetDscp(dscp) != 0) {
1828 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1829 }
1830 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001831
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 LOG(LS_INFO) << "Set voice channel options. Current options: "
1833 << options_.ToString();
1834 return true;
1835}
1836
1837bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1838 const std::vector<AudioCodec>& codecs) {
1839 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 LOG(LS_INFO) << "Setting receive voice codecs:";
1841
1842 std::vector<AudioCodec> new_codecs;
1843 // Find all new codecs. We allow adding new codecs but don't allow changing
1844 // the payload type of codecs that is already configured since we might
1845 // already be receiving packets with that payload type.
1846 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001847 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 AudioCodec old_codec;
1849 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1850 if (old_codec.id != it->id) {
1851 LOG(LS_ERROR) << it->name << " payload type changed.";
1852 return false;
1853 }
1854 } else {
1855 new_codecs.push_back(*it);
1856 }
1857 }
1858 if (new_codecs.empty()) {
1859 // There are no new codecs to configure. Already configured codecs are
1860 // never removed.
1861 return true;
1862 }
1863
1864 if (playout_) {
1865 // Receive codecs can not be changed while playing. So we temporarily
1866 // pause playout.
1867 PausePlayout();
1868 }
1869
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001870 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1872 it != new_codecs.end() && ret; ++it) {
1873 webrtc::CodecInst voe_codec;
1874 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1875 LOG(LS_INFO) << ToString(*it);
1876 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001877 if (default_receive_ssrc_ == 0) {
1878 // Set the receive codecs on the default channel explicitly if the
1879 // default channel is not used by |receive_channels_|, this happens in
1880 // conference mode or in non-conference mode when there is no playout
1881 // channel.
1882 // TODO(xians): Figure out how we use the default channel in conference
1883 // mode.
1884 if (engine()->voe()->codec()->SetRecPayloadType(
1885 voe_channel(), voe_codec) == -1) {
1886 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1887 ret = false;
1888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 }
1890
1891 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001892 for (ChannelMap::iterator it = receive_channels_.begin();
1893 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001895 it->second->channel(), voe_codec) == -1) {
1896 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001897 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 ret = false;
1899 }
1900 }
1901 } else {
1902 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1903 ret = false;
1904 }
1905 }
1906 if (ret) {
1907 recv_codecs_ = codecs;
1908 }
1909
1910 if (desired_playout_ && !playout_) {
1911 ResumePlayout();
1912 }
1913 return ret;
1914}
1915
1916bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001917 int channel, const std::vector<AudioCodec>& codecs) {
1918 // Disable VAD, and FEC unless we know the other side wants them.
1919 engine()->voe()->codec()->SetVADStatus(channel, false);
1920 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1921 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922
1923 // Scan through the list to figure out the codec to use for sending, along
1924 // with the proper configuration for VAD and DTMF.
1925 bool first = true;
1926 webrtc::CodecInst send_codec;
1927 memset(&send_codec, 0, sizeof(send_codec));
1928
1929 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1930 it != codecs.end(); ++it) {
1931 // Ignore codecs we don't know about. The negotiation step should prevent
1932 // this, but double-check to be sure.
1933 webrtc::CodecInst voe_codec;
1934 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001935 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 continue;
1937 }
1938
1939 // If OPUS, change what we send according to the "stereo" codec
1940 // parameter, and not the "channels" parameter. We set
1941 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1942 // the bitrate is not specified, i.e. is zero, we set it to the
1943 // appropriate default value for mono or stereo Opus.
1944 if (IsOpus(*it)) {
1945 if (IsOpusStereoEnabled(*it)) {
1946 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001947 if (!IsValidOpusBitrate(it->bitrate)) {
1948 if (it->bitrate != 0) {
1949 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1950 << it->bitrate
1951 << ") with default opus stereo bitrate: "
1952 << kOpusStereoBitrate;
1953 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 voe_codec.rate = kOpusStereoBitrate;
1955 }
1956 } else {
1957 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001958 if (!IsValidOpusBitrate(it->bitrate)) {
1959 if (it->bitrate != 0) {
1960 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1961 << it->bitrate
1962 << ") with default opus mono bitrate: "
1963 << kOpusMonoBitrate;
1964 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001965 voe_codec.rate = kOpusMonoBitrate;
1966 }
1967 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001968 int bitrate_from_params = GetOpusBitrateFromParams(*it);
1969 if (bitrate_from_params != 0) {
1970 voe_codec.rate = bitrate_from_params;
1971 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 }
1973
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001974 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1975 // about it.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1977 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001978 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
1979 channel, it->id) == -1) {
1980 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
1981 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 }
1984
1985 // Turn voice activity detection/comfort noise on if supported.
1986 // Set the wideband CN payload type appropriately.
1987 // (narrowband always uses the static payload type 13).
1988 if (_stricmp(it->name.c_str(), "CN") == 0) {
1989 webrtc::PayloadFrequencies cn_freq;
1990 switch (it->clockrate) {
1991 case 8000:
1992 cn_freq = webrtc::kFreq8000Hz;
1993 break;
1994 case 16000:
1995 cn_freq = webrtc::kFreq16000Hz;
1996 break;
1997 case 32000:
1998 cn_freq = webrtc::kFreq32000Hz;
1999 break;
2000 default:
2001 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2002 << " not supported.";
2003 continue;
2004 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002005 // Set the CN payloadtype and the VAD status.
2006 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2007 if (cn_freq != webrtc::kFreq8000Hz) {
2008 if (engine()->voe()->codec()->SetSendCNPayloadType(
2009 channel, it->id, cn_freq) == -1) {
2010 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2011 // TODO(ajm): This failure condition will be removed from VoE.
2012 // Restore the return here when we update to a new enough webrtc.
2013 //
2014 // Not returning false because the SetSendCNPayloadType will fail if
2015 // the channel is already sending.
2016 // This can happen if the remote description is applied twice, for
2017 // example in the case of ROAP on top of JSEP, where both side will
2018 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002020 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002021
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002022 // Only turn on VAD if we have a CN payload type that matches the
2023 // clockrate for the codec we are going to use.
2024 if (it->clockrate == send_codec.plfreq) {
2025 LOG(LS_INFO) << "Enabling VAD";
2026 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2027 LOG_RTCERR2(SetVADStatus, channel, true);
2028 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 }
2030 }
2031 }
2032
2033 // We'll use the first codec in the list to actually send audio data.
2034 // Be sure to use the payload type requested by the remote side.
2035 // "red", for FEC audio, is a special case where the actual codec to be
2036 // used is specified in params.
2037 if (first) {
2038 if (_stricmp(it->name.c_str(), "red") == 0) {
2039 // Parse out the RED parameters. If we fail, just ignore RED;
2040 // we don't support all possible params/usage scenarios.
2041 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2042 continue;
2043 }
2044
2045 // Enable redundant encoding of the specified codec. Treat any
2046 // failure as a fatal internal error.
2047 LOG(LS_INFO) << "Enabling FEC";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002048 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2049 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2050 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002051 }
2052 } else {
2053 send_codec = voe_codec;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002054 nack_enabled_ = IsNackEnabled(*it);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002055 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 }
2057 first = false;
2058 // Set the codec immediately, since SetVADStatus() depends on whether
2059 // the current codec is mono or stereo.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002060 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061 return false;
2062 }
2063 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064
2065 // If we're being asked to set an empty list of codecs, due to a buggy client,
2066 // choose the most common format: PCMU
2067 if (first) {
2068 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
2069 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
2070 engine()->FindWebRtcCodec(codec, &send_codec);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002071 if (!SetSendCodec(channel, send_codec))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 return false;
2073 }
2074
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002075 // Always update the |send_codec_| to the currently set send codec.
2076 send_codec_.reset(new webrtc::CodecInst(send_codec));
2077
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002078 if (send_bw_setting_) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002079 SetSendBandwidthInternal(send_bw_bps_);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002080 }
2081
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002082 return true;
2083}
2084
2085bool WebRtcVoiceMediaChannel::SetSendCodecs(
2086 const std::vector<AudioCodec>& codecs) {
2087 dtmf_allowed_ = false;
2088 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2089 it != codecs.end(); ++it) {
2090 // Find the DTMF telephone event "codec".
2091 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2092 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2093 dtmf_allowed_ = true;
2094 }
2095 }
2096
2097 // Cache the codecs in order to configure the channel created later.
2098 send_codecs_ = codecs;
2099 for (ChannelMap::iterator iter = send_channels_.begin();
2100 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002101 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002102 return false;
2103 }
2104 }
2105
2106 SetNack(receive_channels_, nack_enabled_);
2107
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 return true;
2109}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002110
2111void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2112 bool nack_enabled) {
2113 for (ChannelMap::const_iterator it = channels.begin();
2114 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002115 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002116 }
2117}
2118
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002119void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002120 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002121 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2123 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002124 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2126 }
2127}
2128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129bool WebRtcVoiceMediaChannel::SetSendCodec(
2130 const webrtc::CodecInst& send_codec) {
2131 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2132 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002133 for (ChannelMap::iterator iter = send_channels_.begin();
2134 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002135 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002136 return false;
2137 }
2138
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002139 return true;
2140}
2141
2142bool WebRtcVoiceMediaChannel::SetSendCodec(
2143 int channel, const webrtc::CodecInst& send_codec) {
2144 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2145 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2146
2147 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2148 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 return false;
2150 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 return true;
2152}
2153
2154bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2155 const std::vector<RtpHeaderExtension>& extensions) {
2156 // We don't support any incoming extensions headers right now.
2157 return true;
2158}
2159
2160bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2161 const std::vector<RtpHeaderExtension>& extensions) {
2162 // Enable the audio level extension header if requested.
2163 std::vector<RtpHeaderExtension>::const_iterator it;
2164 for (it = extensions.begin(); it != extensions.end(); ++it) {
2165 if (it->uri == kRtpAudioLevelHeaderExtension) {
2166 break;
2167 }
2168 }
2169
2170 bool enable = (it != extensions.end());
2171 int id = 0;
2172
2173 if (enable) {
2174 id = it->id;
2175 if (id < kMinRtpHeaderExtensionId ||
2176 id > kMaxRtpHeaderExtensionId) {
2177 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2178 return false;
2179 }
2180 }
2181
2182 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002183 for (ChannelMap::const_iterator iter = send_channels_.begin();
2184 iter != send_channels_.end(); ++iter) {
2185 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002186 iter->second->channel(), enable, id) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002187 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002188 iter->second->channel(), enable, id);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002189 return false;
2190 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002191 }
2192
2193 return true;
2194}
2195
2196bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2197 desired_playout_ = playout;
2198 return ChangePlayout(desired_playout_);
2199}
2200
2201bool WebRtcVoiceMediaChannel::PausePlayout() {
2202 return ChangePlayout(false);
2203}
2204
2205bool WebRtcVoiceMediaChannel::ResumePlayout() {
2206 return ChangePlayout(desired_playout_);
2207}
2208
2209bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2210 if (playout_ == playout) {
2211 return true;
2212 }
2213
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002214 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002216 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 // Only toggle the default channel if we don't have any other channels.
2218 result = SetPlayout(voe_channel(), playout);
2219 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002220 for (ChannelMap::iterator it = receive_channels_.begin();
2221 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002222 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002223 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002224 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 result = false;
2226 }
2227 }
2228
2229 if (result) {
2230 playout_ = playout;
2231 }
2232 return result;
2233}
2234
2235bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2236 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002237 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238 return ChangeSend(desired_send_);
2239 return true;
2240}
2241
2242bool WebRtcVoiceMediaChannel::PauseSend() {
2243 return ChangeSend(SEND_NOTHING);
2244}
2245
2246bool WebRtcVoiceMediaChannel::ResumeSend() {
2247 return ChangeSend(desired_send_);
2248}
2249
2250bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2251 if (send_ == send) {
2252 return true;
2253 }
2254
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002255 // Change the settings on each send channel.
2256 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 engine()->SetOptionOverrides(options_);
2258
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002259 // Change the settings on each send channel.
2260 for (ChannelMap::iterator iter = send_channels_.begin();
2261 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002262 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002265
2266 // Clear up the options after stopping sending.
2267 if (send == SEND_NOTHING)
2268 engine()->ClearOptionOverrides();
2269
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 send_ = send;
2271 return true;
2272}
2273
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002274bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2275 if (send == SEND_MICROPHONE) {
2276 if (engine()->voe()->base()->StartSend(channel) == -1) {
2277 LOG_RTCERR1(StartSend, channel);
2278 return false;
2279 }
2280 if (engine()->voe()->file() &&
2281 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2282 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2283 return false;
2284 }
2285 } else { // SEND_NOTHING
2286 ASSERT(send == SEND_NOTHING);
2287 if (engine()->voe()->base()->StopSend(channel) == -1) {
2288 LOG_RTCERR1(StopSend, channel);
2289 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002290 }
2291 }
2292
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293 return true;
2294}
2295
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002296void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2297 if (engine()->voe()->network()->RegisterExternalTransport(
2298 channel, *this) == -1) {
2299 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2300 }
2301
2302 // Enable RTCP (for quality stats and feedback messages)
2303 EnableRtcp(channel);
2304
2305 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2306 ResetRecvCodecs(channel);
2307}
2308
2309bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2310 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2311 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2312 }
2313
2314 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2315 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002316 return false;
2317 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002318
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002319 return true;
2320}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002321
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002322bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2323 // If the default channel is already used for sending create a new channel
2324 // otherwise use the default channel for sending.
2325 int channel = GetSendChannelNum(sp.first_ssrc());
2326 if (channel != -1) {
2327 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2328 return false;
2329 }
2330
2331 bool default_channel_is_available = true;
2332 for (ChannelMap::const_iterator iter = send_channels_.begin();
2333 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002334 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002335 default_channel_is_available = false;
2336 break;
2337 }
2338 }
2339 if (default_channel_is_available) {
2340 channel = voe_channel();
2341 } else {
2342 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002343 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 if (channel == -1) {
2345 LOG_RTCERR0(CreateChannel);
2346 return false;
2347 }
2348
2349 ConfigureSendChannel(channel);
2350 }
2351
2352 // Save the channel to send_channels_, so that RemoveSendStream() can still
2353 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002354#ifdef USE_WEBRTC_DEV_BRANCH
2355 webrtc::AudioTransport* audio_transport =
2356 engine()->voe()->base()->audio_transport();
2357#else
2358 webrtc::AudioTransport* audio_transport = NULL;
2359#endif
2360 send_channels_.insert(std::make_pair(
2361 sp.first_ssrc(),
2362 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002363
2364 // Set the send (local) SSRC.
2365 // If there are multiple send SSRCs, we can only set the first one here, and
2366 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2367 // (with a codec requires multiple SSRC(s)).
2368 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2369 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2370 return false;
2371 }
2372
2373 // At this point the channel's local SSRC has been updated. If the channel is
2374 // the default channel make sure that all the receive channels are updated as
2375 // well. Receive channels have to have the same SSRC as the default channel in
2376 // order to send receiver reports with this SSRC.
2377 if (IsDefaultChannel(channel)) {
2378 for (ChannelMap::const_iterator it = receive_channels_.begin();
2379 it != receive_channels_.end(); ++it) {
2380 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002381 if (!IsDefaultChannel(it->second->channel())) {
2382 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002383 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002384 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002385 return false;
2386 }
2387 }
2388 }
2389 }
2390
2391 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2392 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2393 return false;
2394 }
2395
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002396 // Set the current codecs to be used for the new channel.
2397 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002398 return false;
2399
2400 return ChangeSend(channel, desired_send_);
2401}
2402
2403bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2404 ChannelMap::iterator it = send_channels_.find(ssrc);
2405 if (it == send_channels_.end()) {
2406 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2407 << " which doesn't exist.";
2408 return false;
2409 }
2410
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002411 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002412 ChangeSend(channel, SEND_NOTHING);
2413
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002414 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2415 // this will disconnect the audio renderer with the send channel.
2416 delete it->second;
2417 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418
2419 if (IsDefaultChannel(channel)) {
2420 // Do not delete the default channel since the receive channels depend on
2421 // the default channel, recycle it instead.
2422 ChangeSend(channel, SEND_NOTHING);
2423 } else {
2424 // Clean up and delete the send channel.
2425 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2426 << " with VoiceEngine channel #" << channel << ".";
2427 if (!DeleteChannel(channel))
2428 return false;
2429 }
2430
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002431 if (send_channels_.empty())
2432 ChangeSend(SEND_NOTHING);
2433
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 return true;
2435}
2436
2437bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002438 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439
2440 if (!VERIFY(sp.ssrcs.size() == 1))
2441 return false;
2442 uint32 ssrc = sp.first_ssrc();
2443
wu@webrtc.org78187522013-10-07 23:32:02 +00002444 if (ssrc == 0) {
2445 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2446 return false;
2447 }
2448
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002449 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2450 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 return false;
2452 }
2453
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002454 // Reuse default channel for recv stream in non-conference mode call
2455 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002456#ifdef USE_WEBRTC_DEV_BRANCH
2457 webrtc::AudioTransport* audio_transport =
2458 engine()->voe()->base()->audio_transport();
2459#else
2460 webrtc::AudioTransport* audio_transport = NULL;
2461#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002462 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2463 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2464 << " reuse default channel";
2465 default_receive_ssrc_ = sp.first_ssrc();
2466 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002467 default_receive_ssrc_,
2468 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002469 return SetPlayout(voe_channel(), playout_);
2470 }
2471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002473 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474 if (channel == -1) {
2475 LOG_RTCERR0(CreateChannel);
2476 return false;
2477 }
2478
wu@webrtc.org78187522013-10-07 23:32:02 +00002479 if (!ConfigureRecvChannel(channel)) {
2480 DeleteChannel(channel);
2481 return false;
2482 }
2483
2484 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002485 std::make_pair(
2486 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002487
2488 LOG(LS_INFO) << "New audio stream " << ssrc
2489 << " registered to VoiceEngine channel #"
2490 << channel << ".";
2491 return true;
2492}
2493
2494bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 // Configure to use external transport, like our default channel.
2496 if (engine()->voe()->network()->RegisterExternalTransport(
2497 channel, *this) == -1) {
2498 LOG_RTCERR2(SetExternalTransport, channel, this);
2499 return false;
2500 }
2501
2502 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002503 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002504 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2505 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002506 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002507 return false;
2508 }
2509 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002510 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002511 return false;
2512 }
2513
2514 // Use the same recv payload types as our default channel.
2515 ResetRecvCodecs(channel);
2516 if (!recv_codecs_.empty()) {
2517 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2518 it != recv_codecs_.end(); ++it) {
2519 webrtc::CodecInst voe_codec;
2520 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2521 voe_codec.pltype = it->id;
2522 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2523 if (engine()->voe()->codec()->GetRecPayloadType(
2524 voe_channel(), voe_codec) != -1) {
2525 if (engine()->voe()->codec()->SetRecPayloadType(
2526 channel, voe_codec) == -1) {
2527 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2528 return false;
2529 }
2530 }
2531 }
2532 }
2533 }
2534
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002535 if (InConferenceMode()) {
2536 // To be in par with the video, voe_channel() is not used for receiving in
2537 // a conference call.
2538 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2539 // This is the first stream in a multi user meeting. We can now
2540 // disable playback of the default stream. This since the default
2541 // stream will probably have received some initial packets before
2542 // the new stream was added. This will mean that the CN state from
2543 // the default channel will be mixed in with the other streams
2544 // throughout the whole meeting, which might be disturbing.
2545 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2546 SetPlayout(voe_channel(), false);
2547 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002549 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002550
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002551 return SetPlayout(channel, playout_);
2552}
2553
2554bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002555 talk_base::CritScope lock(&receive_channels_cs_);
2556 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002557 if (it == receive_channels_.end()) {
2558 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2559 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002560 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002561 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002563 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2564 // will disconnect the audio renderer with the receive channel.
2565 // Cache the channel before the deletion.
2566 const int channel = it->second->channel();
2567 delete it->second;
2568 receive_channels_.erase(it);
2569
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002570 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002571 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002572 // Recycle the default channel is for recv stream.
2573 if (playout_)
2574 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002575
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002576 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002577 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002579
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002580 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002581 << " with VoiceEngine channel #" << channel << ".";
2582 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002583 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002584
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002585 bool enable_default_channel_playout = false;
2586 if (receive_channels_.empty()) {
2587 // The last stream was removed. We can now enable the default
2588 // channel for new channels to be played out immediately without
2589 // waiting for AddStream messages.
2590 // We do this for both conference mode and non-conference mode.
2591 // TODO(oja): Does the default channel still have it's CN state?
2592 enable_default_channel_playout = true;
2593 }
2594 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2595 default_receive_ssrc_ != 0) {
2596 // Only the default channel is active, enable the playout on default
2597 // channel.
2598 enable_default_channel_playout = true;
2599 }
2600 if (enable_default_channel_playout && playout_) {
2601 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2602 SetPlayout(voe_channel(), true);
2603 }
2604
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002605 return true;
2606}
2607
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002608bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2609 AudioRenderer* renderer) {
2610 ChannelMap::iterator it = receive_channels_.find(ssrc);
2611 if (it == receive_channels_.end()) {
2612 if (renderer) {
2613 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002614 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002615 return false;
2616 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002617
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002618 // The channel likely has gone away, do nothing.
2619 return true;
2620 }
2621
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002622 if (renderer)
2623 it->second->Start(renderer);
2624 else
2625 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002626
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002627 return true;
2628}
2629
2630bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2631 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002632 ChannelMap::iterator it = send_channels_.find(ssrc);
2633 if (it == send_channels_.end()) {
2634 if (renderer) {
2635 // Return an error if trying to set a valid renderer with an invalid ssrc.
2636 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2637 return false;
2638 }
2639
2640 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002641 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002642 }
2643
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002644 if (renderer)
2645 it->second->Start(renderer);
2646 else
2647 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002649 return true;
2650}
2651
2652bool WebRtcVoiceMediaChannel::GetActiveStreams(
2653 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002654 // In conference mode, the default channel should not be in
2655 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002657 for (ChannelMap::iterator it = receive_channels_.begin();
2658 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002659 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002660 if (level > 0) {
2661 actives->push_back(std::make_pair(it->first, level));
2662 }
2663 }
2664 return true;
2665}
2666
2667int WebRtcVoiceMediaChannel::GetOutputLevel() {
2668 // return the highest output level of all streams
2669 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002670 for (ChannelMap::iterator it = receive_channels_.begin();
2671 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002672 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 highest = talk_base::_max(level, highest);
2674 }
2675 return highest;
2676}
2677
2678int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2679 int ret;
2680 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2681 // In case of error, log the info and continue
2682 LOG_RTCERR0(TimeSinceLastTyping);
2683 ret = -1;
2684 } else {
2685 ret *= 1000; // We return ms, webrtc returns seconds.
2686 }
2687 return ret;
2688}
2689
2690void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2691 int cost_per_typing, int reporting_threshold, int penalty_decay,
2692 int type_event_delay) {
2693 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2694 time_window, cost_per_typing,
2695 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2696 // In case of error, log the info and continue
2697 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2698 cost_per_typing, reporting_threshold, penalty_decay,
2699 type_event_delay);
2700 }
2701}
2702
2703bool WebRtcVoiceMediaChannel::SetOutputScaling(
2704 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002705 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 // Collect the channels to scale the output volume.
2707 std::vector<int> channels;
2708 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002709 // Default channel is not in receive_channels_ if it is not being used for
2710 // playout.
2711 if (default_receive_ssrc_ == 0)
2712 channels.push_back(voe_channel());
2713 for (ChannelMap::const_iterator it = receive_channels_.begin();
2714 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002715 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 }
2717 } else { // Collect only the channel of the specified ssrc.
2718 int channel = GetReceiveChannelNum(ssrc);
2719 if (-1 == channel) {
2720 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2721 return false;
2722 }
2723 channels.push_back(channel);
2724 }
2725
2726 // Scale the output volume for the collected channels. We first normalize to
2727 // scale the volume and then set the left and right pan.
2728 float scale = static_cast<float>(talk_base::_max(left, right));
2729 if (scale > 0.0001f) {
2730 left /= scale;
2731 right /= scale;
2732 }
2733 for (std::vector<int>::const_iterator it = channels.begin();
2734 it != channels.end(); ++it) {
2735 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2736 *it, scale)) {
2737 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2738 return false;
2739 }
2740 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2741 *it, static_cast<float>(left), static_cast<float>(right))) {
2742 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2743 // Do not return if fails. SetOutputVolumePan is not available for all
2744 // pltforms.
2745 }
2746 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2747 << " right=" << right * scale
2748 << " for channel " << *it << " and ssrc " << ssrc;
2749 }
2750 return true;
2751}
2752
2753bool WebRtcVoiceMediaChannel::GetOutputScaling(
2754 uint32 ssrc, double* left, double* right) {
2755 if (!left || !right) return false;
2756
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002757 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002758 // Determine which channel based on ssrc.
2759 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2760 if (channel == -1) {
2761 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2762 return false;
2763 }
2764
2765 float scaling;
2766 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2767 channel, scaling)) {
2768 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2769 return false;
2770 }
2771
2772 float left_pan;
2773 float right_pan;
2774 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2775 channel, left_pan, right_pan)) {
2776 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2777 // If GetOutputVolumePan fails, we use the default left and right pan.
2778 left_pan = 1.0f;
2779 right_pan = 1.0f;
2780 }
2781
2782 *left = scaling * left_pan;
2783 *right = scaling * right_pan;
2784 return true;
2785}
2786
2787bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2788 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2789 return true;
2790}
2791
2792bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2793 bool play, bool loop) {
2794 if (!ringback_tone_) {
2795 return false;
2796 }
2797
2798 // The voe file api is not available in chrome.
2799 if (!engine()->voe()->file()) {
2800 return false;
2801 }
2802
2803 // Determine which VoiceEngine channel to play on.
2804 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2805 if (channel == -1) {
2806 return false;
2807 }
2808
2809 // Make sure the ringtone is cued properly, and play it out.
2810 if (play) {
2811 ringback_tone_->set_loop(loop);
2812 ringback_tone_->Rewind();
2813 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2814 ringback_tone_.get()) == -1) {
2815 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2816 LOG(LS_ERROR) << "Unable to start ringback tone";
2817 return false;
2818 }
2819 ringback_channels_.insert(channel);
2820 LOG(LS_INFO) << "Started ringback on channel " << channel;
2821 } else {
2822 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2823 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2824 LOG_RTCERR1(StopPlayingFileLocally, channel);
2825 return false;
2826 }
2827 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2828 ringback_channels_.erase(channel);
2829 }
2830
2831 return true;
2832}
2833
2834bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2835 return dtmf_allowed_;
2836}
2837
2838bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2839 int duration, int flags) {
2840 if (!dtmf_allowed_) {
2841 return false;
2842 }
2843
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844 // Send the event.
2845 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002846 int channel = -1;
2847 if (ssrc == 0) {
2848 bool default_channel_is_inuse = false;
2849 for (ChannelMap::const_iterator iter = send_channels_.begin();
2850 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002851 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002852 default_channel_is_inuse = true;
2853 break;
2854 }
2855 }
2856 if (default_channel_is_inuse) {
2857 channel = voe_channel();
2858 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002859 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002860 }
2861 } else {
2862 channel = GetSendChannelNum(ssrc);
2863 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002864 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2866 << ssrc << " is not in use.";
2867 return false;
2868 }
2869 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002870 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2871 channel, event, true, duration) == -1) {
2872 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 return false;
2874 }
2875 }
2876
2877 // Play the event.
2878 if (flags & cricket::DF_PLAY) {
2879 // Play DTMF tone locally.
2880 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2881 LOG_RTCERR2(PlayDtmfTone, event, duration);
2882 return false;
2883 }
2884 }
2885
2886 return true;
2887}
2888
wu@webrtc.orga9890802013-12-13 00:21:03 +00002889void WebRtcVoiceMediaChannel::OnPacketReceived(
2890 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 // Pick which channel to send this packet to. If this packet doesn't match
2892 // any multiplexed streams, just send it to the default channel. Otherwise,
2893 // send it to the specific decoder instance for that stream.
2894 int which_channel = GetReceiveChannelNum(
2895 ParseSsrc(packet->data(), packet->length(), false));
2896 if (which_channel == -1) {
2897 which_channel = voe_channel();
2898 }
2899
2900 // Stop any ringback that might be playing on the channel.
2901 // It's possible the ringback has already stopped, ih which case we'll just
2902 // use the opportunity to remove the channel from ringback_channels_.
2903 if (engine()->voe()->file()) {
2904 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2905 if (it != ringback_channels_.end()) {
2906 if (engine()->voe()->file()->IsPlayingFileLocally(
2907 which_channel) == 1) {
2908 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2909 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2910 << " due to incoming media";
2911 }
2912 ringback_channels_.erase(which_channel);
2913 }
2914 }
2915
2916 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002917 engine()->voe()->network()->ReceivedRTPPacket(
2918 which_channel,
2919 packet->data(),
2920 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002921}
2922
wu@webrtc.orga9890802013-12-13 00:21:03 +00002923void WebRtcVoiceMediaChannel::OnRtcpReceived(
2924 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002925 // Sending channels need all RTCP packets with feedback information.
2926 // Even sender reports can contain attached report blocks.
2927 // Receiving channels need sender reports in order to create
2928 // correct receiver reports.
2929 int type = 0;
2930 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2931 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2932 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933 }
2934
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002935 // If it is a sender report, find the channel that is listening.
2936 bool has_sent_to_default_channel = false;
2937 if (type == kRtcpTypeSR) {
2938 int which_channel = GetReceiveChannelNum(
2939 ParseSsrc(packet->data(), packet->length(), true));
2940 if (which_channel != -1) {
2941 engine()->voe()->network()->ReceivedRTCPPacket(
2942 which_channel,
2943 packet->data(),
2944 static_cast<unsigned int>(packet->length()));
2945
2946 if (IsDefaultChannel(which_channel))
2947 has_sent_to_default_channel = true;
2948 }
2949 }
2950
2951 // SR may continue RR and any RR entry may correspond to any one of the send
2952 // channels. So all RTCP packets must be forwarded all send channels. VoE
2953 // will filter out RR internally.
2954 for (ChannelMap::iterator iter = send_channels_.begin();
2955 iter != send_channels_.end(); ++iter) {
2956 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002957 if (IsDefaultChannel(iter->second->channel()) &&
2958 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002959 continue;
2960
2961 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002962 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002963 packet->data(),
2964 static_cast<unsigned int>(packet->length()));
2965 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966}
2967
2968bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002969 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2970 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2972 return false;
2973 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002974 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2975 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002976 return false;
2977 }
2978 return true;
2979}
2980
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002981bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
2982 // TODO(andresp): Add support for setting an independent start bandwidth when
2983 // bandwidth estimation is enabled for voice engine.
2984 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002985}
2986
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002987bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
2988 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
2989
2990 return SetSendBandwidthInternal(bps);
2991}
2992
2993bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
2994 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
2995
2996 send_bw_setting_ = true;
2997 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002998
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002999 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003000 LOG(LS_INFO) << "The send codec has not been set up yet. "
3001 << "The send bandwidth setting will be applied later.";
3002 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003003 }
3004
3005 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003006 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3007 // SetMaxSendBandwith(0), the second call removes the previous limit.
3008 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003009 return true;
3010
3011 webrtc::CodecInst codec = *send_codec_;
3012 bool is_multi_rate = IsCodecMultiRate(codec);
3013
3014 if (is_multi_rate) {
3015 // If codec is multi-rate then just set the bitrate.
3016 codec.rate = bps;
3017 if (!SetSendCodec(codec)) {
3018 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3019 << " to bitrate " << bps << " bps.";
3020 return false;
3021 }
3022 return true;
3023 } else {
3024 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3025 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3026 // fixed bitrate then ignore.
3027 if (bps < codec.rate) {
3028 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3029 << " to bitrate " << bps << " bps"
3030 << ", requires at least " << codec.rate << " bps.";
3031 return false;
3032 }
3033 return true;
3034 }
3035}
3036
3037bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003038 bool echo_metrics_on = false;
3039 // These can take on valid negative values, so use the lowest possible level
3040 // as default rather than -1.
3041 int echo_return_loss = -100;
3042 int echo_return_loss_enhancement = -100;
3043 // These can also be negative, but in practice -1 is only used to signal
3044 // insufficient data, since the resolution is limited to multiples of 4 ms.
3045 int echo_delay_median_ms = -1;
3046 int echo_delay_std_ms = -1;
3047 if (engine()->voe()->processing()->GetEcMetricsStatus(
3048 echo_metrics_on) != -1 && echo_metrics_on) {
3049 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3050 // here, but it appears to be unsuitable currently. Revisit after this is
3051 // investigated: http://b/issue?id=5666755
3052 int erl, erle, rerl, anlp;
3053 if (engine()->voe()->processing()->GetEchoMetrics(
3054 erl, erle, rerl, anlp) != -1) {
3055 echo_return_loss = erl;
3056 echo_return_loss_enhancement = erle;
3057 }
3058
3059 int median, std;
3060 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3061 echo_delay_median_ms = median;
3062 echo_delay_std_ms = std;
3063 }
3064 }
3065
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066 webrtc::CallStatistics cs;
3067 unsigned int ssrc;
3068 webrtc::CodecInst codec;
3069 unsigned int level;
3070
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003071 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3072 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003073 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003074
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003075 // Fill in the sender info, based on what we know, and what the
3076 // remote side told us it got from its RTCP report.
3077 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3080 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3081 continue;
3082 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003084 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003085 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3086 sinfo.bytes_sent = cs.bytesSent;
3087 sinfo.packets_sent = cs.packetsSent;
3088 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3089 // returns 0 to indicate an error value.
3090 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3091
3092 // Get data from the last remote RTCP report. Use default values if no data
3093 // available.
3094 sinfo.fraction_lost = -1.0;
3095 sinfo.jitter_ms = -1;
3096 sinfo.packets_lost = -1;
3097 sinfo.ext_seqnum = -1;
3098 std::vector<webrtc::ReportBlock> receive_blocks;
3099 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3100 channel, &receive_blocks) != -1 &&
3101 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3102 std::vector<webrtc::ReportBlock>::iterator iter;
3103 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3104 ++iter) {
3105 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003106 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003107 // Convert Q8 to floating point.
3108 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3109 // Convert samples to milliseconds.
3110 if (codec.plfreq / 1000 > 0) {
3111 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3112 }
3113 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3114 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3115 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117 }
3118 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003119
3120 // Local speech level.
3121 sinfo.audio_level = (engine()->voe()->volume()->
3122 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3123
3124 // TODO(xians): We are injecting the same APM logging to all the send
3125 // channels here because there is no good way to know which send channel
3126 // is using the APM. The correct fix is to allow the send channels to have
3127 // their own APM so that we can feed the correct APM logging to different
3128 // send channels. See issue crbug/264611 .
3129 sinfo.echo_return_loss = echo_return_loss;
3130 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3131 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3132 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003133 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3134 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003135 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003136
3137 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 }
3139
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003140 // Build the list of receivers, one for each receiving channel, or 1 in
3141 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003142 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003143 for (ChannelMap::const_iterator it = receive_channels_.begin();
3144 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003145 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 }
3147 if (channels.empty()) {
3148 channels.push_back(voe_channel());
3149 }
3150
3151 // Get the SSRC and stats for each receiver, based on our own calculations.
3152 for (std::vector<int>::const_iterator it = channels.begin();
3153 it != channels.end(); ++it) {
3154 memset(&cs, 0, sizeof(cs));
3155 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3156 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3157 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3158 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003159 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160 rinfo.bytes_rcvd = cs.bytesReceived;
3161 rinfo.packets_rcvd = cs.packetsReceived;
3162 // The next four fields are from the most recently sent RTCP report.
3163 // Convert Q8 to floating point.
3164 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3165 rinfo.packets_lost = cs.cumulativeLost;
3166 rinfo.ext_seqnum = cs.extendedMax;
3167 // Convert samples to milliseconds.
3168 if (codec.plfreq / 1000 > 0) {
3169 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3170 }
3171
3172 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3173 webrtc::NetworkStatistics ns;
3174 if (engine()->voe()->neteq() &&
3175 engine()->voe()->neteq()->GetNetworkStatistics(
3176 *it, ns) != -1) {
3177 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3178 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3179 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003180 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181 }
3182 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003183 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184 int playout_buffer_delay_ms = 0;
3185 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003186 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3187 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3188 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 }
3190
3191 // Get speech level.
3192 rinfo.audio_level = (engine()->voe()->volume()->
3193 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3194 info->receivers.push_back(rinfo);
3195 }
3196 }
3197
3198 return true;
3199}
3200
3201void WebRtcVoiceMediaChannel::GetLastMediaError(
3202 uint32* ssrc, VoiceMediaChannel::Error* error) {
3203 ASSERT(ssrc != NULL);
3204 ASSERT(error != NULL);
3205 FindSsrc(voe_channel(), ssrc);
3206 *error = WebRtcErrorToChannelError(GetLastEngineError());
3207}
3208
3209bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003210 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003212 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3214 // This means the error is not limited to a specific channel. Signal the
3215 // message using ssrc=0. If the current channel is sending, use this
3216 // channel for sending the message.
3217 *ssrc = 0;
3218 return true;
3219 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003220 // Check whether this is a sending channel.
3221 for (ChannelMap::const_iterator it = send_channels_.begin();
3222 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003223 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003224 // This is a sending channel.
3225 uint32 local_ssrc = 0;
3226 if (engine()->voe()->rtp()->GetLocalSSRC(
3227 channel_num, local_ssrc) != -1) {
3228 *ssrc = local_ssrc;
3229 }
3230 return true;
3231 }
3232 }
3233
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003235 for (ChannelMap::const_iterator it = receive_channels_.begin();
3236 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003237 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238 *ssrc = it->first;
3239 return true;
3240 }
3241 }
3242 }
3243 return false;
3244}
3245
3246void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003247 if (error == VE_TYPING_NOISE_WARNING) {
3248 typing_noise_detected_ = true;
3249 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3250 typing_noise_detected_ = false;
3251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003252 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3253}
3254
3255int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3256 unsigned int ulevel;
3257 int ret =
3258 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3259 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3260}
3261
3262int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003263 ChannelMap::iterator it = receive_channels_.find(ssrc);
3264 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003265 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3267}
3268
3269int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003270 ChannelMap::iterator it = send_channels_.find(ssrc);
3271 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003272 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003273
3274 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275}
3276
3277bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3278 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3279 // Get the RED encodings from the parameter with no name. This may
3280 // change based on what is discussed on the Jingle list.
3281 // The encoding parameter is of the form "a/b"; we only support where
3282 // a == b. Verify this and parse out the value into red_pt.
3283 // If the parameter value is absent (as it will be until we wire up the
3284 // signaling of this message), use the second codec specified (i.e. the
3285 // one after "red") as the encoding parameter.
3286 int red_pt = -1;
3287 std::string red_params;
3288 CodecParameterMap::const_iterator it = red_codec.params.find("");
3289 if (it != red_codec.params.end()) {
3290 red_params = it->second;
3291 std::vector<std::string> red_pts;
3292 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3293 red_pts[0] != red_pts[1] ||
3294 !talk_base::FromString(red_pts[0], &red_pt)) {
3295 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3296 return false;
3297 }
3298 } else if (red_codec.params.empty()) {
3299 LOG(LS_WARNING) << "RED params not present, using defaults";
3300 if (all_codecs.size() > 1) {
3301 red_pt = all_codecs[1].id;
3302 }
3303 }
3304
3305 // Try to find red_pt in |codecs|.
3306 std::vector<AudioCodec>::const_iterator codec;
3307 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3308 if (codec->id == red_pt)
3309 break;
3310 }
3311
3312 // If we find the right codec, that will be the codec we pass to
3313 // SetSendCodec, with the desired payload type.
3314 if (codec != all_codecs.end() &&
3315 engine()->FindWebRtcCodec(*codec, send_codec)) {
3316 } else {
3317 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3318 return false;
3319 }
3320
3321 return true;
3322}
3323
3324bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3325 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003326 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003327 return false;
3328 }
3329 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3330 // what we want to do with them.
3331 // engine()->voe().EnableVQMon(voe_channel(), true);
3332 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3333 return true;
3334}
3335
3336bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3337 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3338 for (int i = 0; i < ncodecs; ++i) {
3339 webrtc::CodecInst voe_codec;
3340 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3341 voe_codec.pltype = -1;
3342 if (engine()->voe()->codec()->SetRecPayloadType(
3343 channel, voe_codec) == -1) {
3344 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3345 return false;
3346 }
3347 }
3348 }
3349 return true;
3350}
3351
3352bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3353 if (playout) {
3354 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3355 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3356 LOG_RTCERR1(StartPlayout, channel);
3357 return false;
3358 }
3359 } else {
3360 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3361 engine()->voe()->base()->StopPlayout(channel);
3362 }
3363 return true;
3364}
3365
3366uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3367 bool rtcp) {
3368 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3369 uint32 ssrc = 0;
3370 if (len >= (ssrc_pos + sizeof(ssrc))) {
3371 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3372 }
3373 return ssrc;
3374}
3375
3376// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3377VoiceMediaChannel::Error
3378 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3379 switch (err_code) {
3380 case 0:
3381 return ERROR_NONE;
3382 case VE_CANNOT_START_RECORDING:
3383 case VE_MIC_VOL_ERROR:
3384 case VE_GET_MIC_VOL_ERROR:
3385 case VE_CANNOT_ACCESS_MIC_VOL:
3386 return ERROR_REC_DEVICE_OPEN_FAILED;
3387 case VE_SATURATION_WARNING:
3388 return ERROR_REC_DEVICE_SATURATION;
3389 case VE_REC_DEVICE_REMOVED:
3390 return ERROR_REC_DEVICE_REMOVED;
3391 case VE_RUNTIME_REC_WARNING:
3392 case VE_RUNTIME_REC_ERROR:
3393 return ERROR_REC_RUNTIME_ERROR;
3394 case VE_CANNOT_START_PLAYOUT:
3395 case VE_SPEAKER_VOL_ERROR:
3396 case VE_GET_SPEAKER_VOL_ERROR:
3397 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3398 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3399 case VE_RUNTIME_PLAY_WARNING:
3400 case VE_RUNTIME_PLAY_ERROR:
3401 return ERROR_PLAY_RUNTIME_ERROR;
3402 case VE_TYPING_NOISE_WARNING:
3403 return ERROR_REC_TYPING_NOISE_DETECTED;
3404 default:
3405 return VoiceMediaChannel::ERROR_OTHER;
3406 }
3407}
3408
3409int WebRtcSoundclipStream::Read(void *buf, int len) {
3410 size_t res = 0;
3411 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003412 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413}
3414
3415int WebRtcSoundclipStream::Rewind() {
3416 mem_.Rewind();
3417 // Return -1 to keep VoiceEngine from looping.
3418 return (loop_) ? 0 : -1;
3419}
3420
3421} // namespace cricket
3422
3423#endif // HAVE_WEBRTC_VOICE