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