blob: f20b5e154e9a2c5738825b1c65ef6e2772596a1a [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
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.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"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
Brave Yao5225dd82015-03-26 07:39:19 +080063static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064struct CodecPref {
65 const char* name;
66 int clockrate;
67 int channels;
68 int payload_type;
69 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080070 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071};
Brave Yao5225dd82015-03-26 07:39:19 +080072// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
75 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
76 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
79 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
80 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
81 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
82 { kCnCodecName, 48000, 1, 107, false, { } },
83 { kCnCodecName, 32000, 1, 106, false, { } },
84 { kCnCodecName, 16000, 1, 105, false, { } },
85 { kCnCodecName, 8000, 1, 13, false, { } },
86 { kRedCodecName, 8000, 1, 127, false, { } },
87 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088};
89
90// For Linux/Mac, using the default device is done by specifying index 0 for
91// VoE 4.0 and not -1 (which was the case for VoE 3.5).
92//
93// On Windows Vista and newer, Microsoft introduced the concept of "Default
94// Communications Device". This means that there are two types of default
95// devices (old Wave Audio style default and Default Communications Device).
96//
97// On Windows systems which only support Wave Audio style default, uses either
98// -1 or 0 to select the default device.
99//
100// On Windows systems which support both "Default Communication Device" and
101// old Wave Audio style default, use -1 for Default Communications Device and
102// -2 for Wave Audio style default, which is what we want to use for clips.
103// It's not clear yet whether the -2 index is handled properly on other OSes.
104
105#ifdef WIN32
106static const int kDefaultAudioDeviceId = -1;
107static const int kDefaultSoundclipDeviceId = -2;
108#else
109static const int kDefaultAudioDeviceId = 0;
110#endif
111
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112// Parameter used for NACK.
113// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
114static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000115
116// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000117// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000118
119// Recommended bitrates:
120// 8-12 kb/s for NB speech,
121// 16-20 kb/s for WB speech,
122// 28-40 kb/s for FB speech,
123// 48-64 kb/s for FB mono music, and
124// 64-128 kb/s for FB stereo music.
125// The current implementation applies the following values to mono signals,
126// and multiplies them by 2 for stereo.
127static const int kOpusBitrateNb = 12000;
128static const int kOpusBitrateWb = 20000;
129static const int kOpusBitrateFb = 32000;
130
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000131// Opus bitrate should be in the range between 6000 and 510000.
132static const int kOpusMinBitrate = 6000;
133static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000134
wu@webrtc.orgde305012013-10-31 15:40:38 +0000135// Default audio dscp value.
136// See http://tools.ietf.org/html/rfc2474 for details.
137// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000138static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000139
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// Ensure we open the file in a writeable path on ChromeOS and Android. This
141// workaround can be removed when it's possible to specify a filename for audio
142// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143//
144// TODO(grunell): Use a string in the options instead of hardcoding it here
145// and let the embedder choose the filename (crbug.com/264223).
146//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000147// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
148// below.
149#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000150static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000151#elif defined(ANDROID)
152static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000153#else
154static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
155#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000156
157// Dumps an AudioCodec in RFC 2327-ish format.
158static std::string ToString(const AudioCodec& codec) {
159 std::stringstream ss;
160 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
161 << " (" << codec.id << ")";
162 return ss.str();
163}
164static std::string ToString(const webrtc::CodecInst& codec) {
165 std::stringstream ss;
166 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
167 << " (" << codec.pltype << ")";
168 return ss.str();
169}
170
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 const char* delim = "\r\n";
173 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
174 LOG_V(sev) << tok;
175 }
176}
177
178// Severity is an integer because it comes is assumed to be from command line.
179static int SeverityToFilter(int severity) {
180 int filter = webrtc::kTraceNone;
181 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000182 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
190 }
191 return filter;
192}
193
194static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
195 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
196 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
197 kCodecPrefs[i].clockrate == codec.plfreq) {
198 return kCodecPrefs[i].is_multi_rate;
199 }
200 }
201 return false;
202}
203
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000204static bool IsTelephoneEventCodec(const std::string& name) {
205 return _stricmp(name.c_str(), "telephone-event") == 0;
206}
207
208static bool IsCNCodec(const std::string& name) {
209 return _stricmp(name.c_str(), "CN") == 0;
210}
211
212static bool IsRedCodec(const std::string& name) {
213 return _stricmp(name.c_str(), "red") == 0;
214}
215
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216static bool FindCodec(const std::vector<AudioCodec>& codecs,
217 const AudioCodec& codec,
218 AudioCodec* found_codec) {
219 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
220 it != codecs.end(); ++it) {
221 if (it->Matches(codec)) {
222 if (found_codec != NULL) {
223 *found_codec = *it;
224 }
225 return true;
226 }
227 }
228 return false;
229}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000230
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231static bool IsNackEnabled(const AudioCodec& codec) {
232 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
233 kParamValueEmpty));
234}
235
Brave Yao5225dd82015-03-26 07:39:19 +0800236static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
237 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
238 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
239 if (packet_size_ms && packet_size_ms <= ptime_ms) {
240 selected_packet_size_ms = packet_size_ms;
241 }
242 }
243 return selected_packet_size_ms;
244}
245
246// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
247// pacsize if it's valid, or we will pick the next smallest value we support.
248// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
249static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
250 for (const CodecPref& codec_pref : kCodecPrefs) {
251 if ((_stricmp(codec_pref.name, codec->plname) == 0 &&
252 codec_pref.clockrate == codec->plfreq) ||
253 _stricmp(codec_pref.name, kG722CodecName) == 0) {
254 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
255 if (packet_size_ms) {
256 // Convert unit from milli-seconds to samples.
257 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
258 return true;
259 }
260 }
261 }
262 return false;
263}
264
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000265// Gets the default set of options applied to the engine. Historically, these
266// were supplied as a combination of flags from the channel manager (ec, agc,
267// ns, and highpass) and the rest hardcoded in InitInternal.
268static AudioOptions GetDefaultEngineOptions() {
269 AudioOptions options;
270 options.echo_cancellation.Set(true);
271 options.auto_gain_control.Set(true);
272 options.noise_suppression.Set(true);
273 options.highpass_filter.Set(true);
274 options.stereo_swapping.Set(false);
275 options.typing_detection.Set(true);
276 options.conference_mode.Set(false);
277 options.adjust_agc_delta.Set(0);
278 options.experimental_agc.Set(false);
279 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100280 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000281 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000282 options.aec_dump.Set(false);
283 return options;
284}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000285
Brave Yao5225dd82015-03-26 07:39:19 +0800286static bool IsOpus(const AudioCodec& codec) {
287 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
288}
289
290static bool IsIsac(const AudioCodec& codec) {
291 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
292}
293
294// True if params["stereo"] == "1"
295static bool IsOpusStereoEnabled(const AudioCodec& codec) {
296 int value;
297 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
298}
299
300// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
301// otherwise. If the value (either from params or codec.bitrate) <=0, use the
302// default configuration. If the value is beyond feasible bit rate of Opus,
303// clamp it. Returns the Opus bit rate for operation.
304static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
305 int bitrate = 0;
306 bool use_param = true;
307 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
308 bitrate = codec.bitrate;
309 use_param = false;
310 }
311 if (bitrate <= 0) {
312 if (max_playback_rate <= 8000) {
313 bitrate = kOpusBitrateNb;
314 }
315 else if (max_playback_rate <= 16000) {
316 bitrate = kOpusBitrateWb;
317 }
318 else {
319 bitrate = kOpusBitrateFb;
320 }
321
322 if (IsOpusStereoEnabled(codec)) {
323 bitrate *= 2;
324 }
325 }
326 else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
327 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
328 std::string rate_source =
329 use_param ? "Codec parameter \"maxaveragebitrate\"" :
330 "Supplied Opus bitrate";
331 LOG(LS_WARNING) << rate_source
332 << " is invalid and is replaced by: "
333 << bitrate;
334 }
335 return bitrate;
336}
337
338// Return true if params[kCodecParamUseInbandFec] == "1", false
339// otherwise.
340static bool IsOpusFecEnabled(const AudioCodec& codec) {
341 int value;
342 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
343}
344
345// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
346// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
347static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
348 int value;
349 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
350 return value;
351 }
352 return kOpusDefaultMaxPlaybackRate;
353}
354
355static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
356 bool* enable_codec_fec, int* max_playback_rate) {
357 *enable_codec_fec = IsOpusFecEnabled(codec);
358 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
359
360 // If OPUS, change what we send according to the "stereo" codec
361 // parameter, and not the "channels" parameter. We set
362 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
363 // the bitrate is not specified, i.e. is <= zero, we set it to the
364 // appropriate default value for mono or stereo Opus.
365
366 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
367 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
368}
369
370// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
371// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
372// codec.
373static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
374 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
375 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
376 // has changed, and this special case is no longer needed.
377 ASSERT(voe_codec->plfreq != new_plfreq);
378 voe_codec->plfreq = new_plfreq;
379 }
380}
381
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000382class WebRtcSoundclipMedia : public SoundclipMedia {
383 public:
384 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
385 : engine_(engine), webrtc_channel_(-1) {
386 engine_->RegisterSoundclip(this);
387 }
388
389 virtual ~WebRtcSoundclipMedia() {
390 engine_->UnregisterSoundclip(this);
391 if (webrtc_channel_ != -1) {
392 // We shouldn't have to call Disable() here. DeleteChannel() should call
393 // StopPlayout() while deleting the channel. We should fix the bug
394 // inside WebRTC and remove the Disable() call bellow. This work is
395 // tracked by bug http://b/issue?id=5382855.
396 PlaySound(NULL, 0, 0);
397 Disable();
398 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
399 == -1) {
400 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
401 }
402 }
403 }
404
405 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000406 if (!engine_->voe_sc()) {
407 return false;
408 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000409 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000410 if (webrtc_channel_ == -1) {
411 LOG_RTCERR0(CreateChannel);
412 return false;
413 }
414 return true;
415 }
416
417 bool Enable() {
418 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
419 LOG_RTCERR1(StartPlayout, webrtc_channel_);
420 return false;
421 }
422 return true;
423 }
424
425 bool Disable() {
426 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
427 LOG_RTCERR1(StopPlayout, webrtc_channel_);
428 return false;
429 }
430 return true;
431 }
432
433 virtual bool PlaySound(const char *buf, int len, int flags) {
434 // The voe file api is not available in chrome.
435 if (!engine_->voe_sc()->file()) {
436 return false;
437 }
438 // Must stop playing the current sound (if any), because we are about to
439 // modify the stream.
440 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
441 == -1) {
442 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
443 return false;
444 }
445
446 if (buf) {
447 stream_.reset(new WebRtcSoundclipStream(buf, len));
448 stream_->set_loop((flags & SF_LOOP) != 0);
449 stream_->Rewind();
450
451 // Play it.
452 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
453 webrtc_channel_, stream_.get()) == -1) {
454 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
455 LOG(LS_ERROR) << "Unable to start soundclip";
456 return false;
457 }
458 } else {
459 stream_.reset();
460 }
461 return true;
462 }
463
464 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
465
466 private:
467 WebRtcVoiceEngine *engine_;
468 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000469 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000470};
471
472WebRtcVoiceEngine::WebRtcVoiceEngine()
473 : voe_wrapper_(new VoEWrapper()),
474 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000475 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000476 tracing_(new VoETraceWrapper()),
477 adm_(NULL),
478 adm_sc_(NULL),
479 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
480 is_dumping_aec_(false),
481 desired_local_monitor_enable_(false),
482 tx_processor_ssrc_(0),
483 rx_processor_ssrc_(0) {
484 Construct();
485}
486
487WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
488 VoEWrapper* voe_wrapper_sc,
489 VoETraceWrapper* tracing)
490 : voe_wrapper_(voe_wrapper),
491 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000492 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493 tracing_(tracing),
494 adm_(NULL),
495 adm_sc_(NULL),
496 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
497 is_dumping_aec_(false),
498 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000499 tx_processor_ssrc_(0),
500 rx_processor_ssrc_(0) {
501 Construct();
502}
503
504void WebRtcVoiceEngine::Construct() {
505 SetTraceFilter(log_filter_);
506 initialized_ = false;
507 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
508 SetTraceOptions("");
509 if (tracing_->SetTraceCallback(this) == -1) {
510 LOG_RTCERR0(SetTraceCallback);
511 }
512 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
513 LOG_RTCERR0(RegisterVoiceEngineObserver);
514 }
515 // Clear the default agc state.
516 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
517
518 // Load our audio codec list.
519 ConstructCodecs();
520
521 // Load our RTP Header extensions.
522 rtp_header_extensions_.push_back(
523 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
524 kRtpAudioLevelHeaderExtensionDefaultId));
525 rtp_header_extensions_.push_back(
526 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
527 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
528 options_ = GetDefaultEngineOptions();
529}
530
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531void WebRtcVoiceEngine::ConstructCodecs() {
532 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
533 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
534 for (int i = 0; i < ncodecs; ++i) {
535 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000536 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537 // Skip uncompressed formats.
538 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
539 continue;
540 }
541
542 const CodecPref* pref = NULL;
543 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
544 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
545 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
546 kCodecPrefs[j].channels == voe_codec.channels) {
547 pref = &kCodecPrefs[j];
548 break;
549 }
550 }
551
552 if (pref) {
553 // Use the payload type that we've configured in our pref table;
554 // use the offset in our pref table to determine the sort order.
555 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
556 voe_codec.rate, voe_codec.channels,
557 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
558 LOG(LS_INFO) << ToString(codec);
559 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000560 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000561 codec.bitrate = 0;
562 }
563 if (IsOpus(codec)) {
564 // Only add fmtp parameters that differ from the spec.
565 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
566 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000567 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568 }
569 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
570 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000571 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000572 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000573 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000574
575 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 // when they can be set to values other than the default.
577 }
578 codecs_.push_back(codec);
579 } else {
580 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
581 }
582 }
583 }
584 // Make sure they are in local preference order.
585 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
586}
587
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000588bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
589 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
590 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000591 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000592 // Change the sample rate of G722 to 8000 to match SDP.
593 MaybeFixupG722(codec, 8000);
594 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000595}
596
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000597WebRtcVoiceEngine::~WebRtcVoiceEngine() {
598 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
599 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
600 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
601 }
602 if (adm_) {
603 voe_wrapper_.reset();
604 adm_->Release();
605 adm_ = NULL;
606 }
607 if (adm_sc_) {
608 voe_wrapper_sc_.reset();
609 adm_sc_->Release();
610 adm_sc_ = NULL;
611 }
612
613 // Test to see if the media processor was deregistered properly
614 ASSERT(SignalRxMediaFrame.is_empty());
615 ASSERT(SignalTxMediaFrame.is_empty());
616
617 tracing_->SetTraceCallback(NULL);
618}
619
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000620bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000621 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000622 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
623 bool res = InitInternal();
624 if (res) {
625 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
626 } else {
627 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
628 Terminate();
629 }
630 return res;
631}
632
633bool WebRtcVoiceEngine::InitInternal() {
634 // Temporarily turn logging level up for the Init call
635 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000636 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000637 SetTraceFilter(extended_filter);
638 SetTraceOptions("");
639
640 // Init WebRtc VoiceEngine.
641 if (voe_wrapper_->base()->Init(adm_) == -1) {
642 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
643 SetTraceFilter(old_filter);
644 return false;
645 }
646
647 SetTraceFilter(old_filter);
648 SetTraceOptions(log_options_);
649
650 // Log the VoiceEngine version info
651 char buffer[1024] = "";
652 voe_wrapper_->base()->GetVersion(buffer);
653 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000654 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000655
656 // Save the default AGC configuration settings. This must happen before
657 // calling SetOptions or the default will be overwritten.
658 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
659 LOG_RTCERR0(GetAgcConfig);
660 return false;
661 }
662
663 // Set defaults for options, so that ApplyOptions applies them explicitly
664 // when we clear option (channel) overrides. External clients can still
665 // modify the defaults via SetOptions (on the media engine).
666 if (!SetOptions(GetDefaultEngineOptions())) {
667 return false;
668 }
669
670 // Print our codec list again for the call diagnostic log
671 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
672 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
673 it != codecs_.end(); ++it) {
674 LOG(LS_INFO) << ToString(*it);
675 }
676
677 // Disable the DTMF playout when a tone is sent.
678 // PlayDtmfTone will be used if local playout is needed.
679 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
680 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
681 }
682
683 initialized_ = true;
684 return true;
685}
686
687bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
688 if (voe_wrapper_sc_initialized_) {
689 return true;
690 }
691 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
692 // be false, so subsequent calls to EnsureSoundclipEngineInit will
693 // probably just fail again. That's acceptable behavior.
694#if defined(LINUX) && !defined(HAVE_LIBPULSE)
695 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
696#endif
697
698 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
699 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
700 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
701 return false;
702 }
703
704 // On Windows, tell it to use the default sound (not communication) devices.
705 // First check whether there is a valid sound device for playback.
706 // TODO(juberti): Clean this up when we support setting the soundclip device.
707#ifdef WIN32
708 // The SetPlayoutDevice may not be implemented in the case of external ADM.
709 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
710 // PeerConnection interface never set the adm_sc_, so need to check both
711 // in order to determine if the external adm is used.
712 if (!adm_ && !adm_sc_) {
713 int num_of_devices = 0;
714 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
715 num_of_devices > 0) {
716 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
717 == -1) {
718 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
719 voe_wrapper_sc_->error());
720 return false;
721 }
722 } else {
723 LOG(LS_WARNING) << "No valid sound playout device found.";
724 }
725 }
726#endif
727 voe_wrapper_sc_initialized_ = true;
728 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
729 return true;
730}
731
732void WebRtcVoiceEngine::Terminate() {
733 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
734 initialized_ = false;
735
736 StopAecDump();
737
738 if (voe_wrapper_sc_) {
739 voe_wrapper_sc_initialized_ = false;
740 voe_wrapper_sc_->base()->Terminate();
741 }
742 voe_wrapper_->base()->Terminate();
743 desired_local_monitor_enable_ = false;
744}
745
746int WebRtcVoiceEngine::GetCapabilities() {
747 return AUDIO_SEND | AUDIO_RECV;
748}
749
750VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
751 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
752 if (!ch->valid()) {
753 delete ch;
754 ch = NULL;
755 }
756 return ch;
757}
758
759SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
760 if (!EnsureSoundclipEngineInit()) {
761 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
762 << "initialize.";
763 return NULL;
764 }
765 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
766 if (!soundclip->Init() || !soundclip->Enable()) {
767 delete soundclip;
768 return NULL;
769 }
770 return soundclip;
771}
772
773bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
774 if (!ApplyOptions(options)) {
775 return false;
776 }
777 options_ = options;
778 return true;
779}
780
781bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
782 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
783 if (!ApplyOptions(overrides)) {
784 return false;
785 }
786 option_overrides_ = overrides;
787 return true;
788}
789
790bool WebRtcVoiceEngine::ClearOptionOverrides() {
791 LOG(LS_INFO) << "Clearing option overrides.";
792 AudioOptions options = options_;
793 // Only call ApplyOptions if |options_overrides_| contains overrided options.
794 // ApplyOptions affects NS, AGC other options that is shared between
795 // all WebRtcVoiceEngineChannels.
796 if (option_overrides_ == AudioOptions()) {
797 return true;
798 }
799
800 if (!ApplyOptions(options)) {
801 return false;
802 }
803 option_overrides_ = AudioOptions();
804 return true;
805}
806
807// AudioOptions defaults are set in InitInternal (for options with corresponding
808// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
809bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
810 AudioOptions options = options_in; // The options are modified below.
811 // kEcConference is AEC with high suppression.
812 webrtc::EcModes ec_mode = webrtc::kEcConference;
813 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
814 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
815 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
816 bool aecm_comfort_noise = false;
817 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
818 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
819 << aecm_comfort_noise << " (default is false).";
820 }
821
822#if defined(IOS)
823 // On iOS, VPIO provides built-in EC and AGC.
824 options.echo_cancellation.Set(false);
825 options.auto_gain_control.Set(false);
826#elif defined(ANDROID)
827 ec_mode = webrtc::kEcAecm;
828#endif
829
830#if defined(IOS) || defined(ANDROID)
831 // Set the AGC mode for iOS as well despite disabling it above, to avoid
832 // unsupported configuration errors from webrtc.
833 agc_mode = webrtc::kAgcFixedDigital;
834 options.typing_detection.Set(false);
835 options.experimental_agc.Set(false);
836 options.experimental_aec.Set(false);
837 options.experimental_ns.Set(false);
838#endif
839
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100840 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
841 // where the feature is not supported.
842 bool use_delay_agnostic_aec = false;
843#if !defined(IOS)
844 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
845 if (use_delay_agnostic_aec) {
846 options.echo_cancellation.Set(true);
847 options.experimental_aec.Set(true);
848 ec_mode = webrtc::kEcConference;
849 }
850 }
851#endif
852
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000853 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
854
855 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
856
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000857 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000858 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000859 // Check if platform supports built-in EC. Currently only supported on
860 // Android and in combination with Java based audio layer.
861 // TODO(henrika): investigate possibility to support built-in EC also
862 // in combination with Open SL ES audio.
863 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
864 if (built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100865 // Enabled built-in EC if the device has one and delay agnostic AEC is not
866 // enabled.
867 const bool enable_built_in_aec = echo_cancellation &
868 !use_delay_agnostic_aec;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000869 // Set mode of built-in EC according to the audio options.
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100870 voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec);
871 if (enable_built_in_aec) {
872 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000873 // i.e., replace the software EC with the built-in EC.
874 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000875 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000876 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
877 }
878 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000879 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
880 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
881 return false;
882 } else {
883 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
884 << " with mode " << ec_mode;
885 }
886#if !defined(ANDROID)
887 // TODO(ajm): Remove the error return on Android from webrtc.
888 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
889 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
890 return false;
891 }
892#endif
893 if (ec_mode == webrtc::kEcAecm) {
894 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
895 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
896 return false;
897 }
898 }
899 }
900
901 bool auto_gain_control;
902 if (options.auto_gain_control.Get(&auto_gain_control)) {
903 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
904 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
905 return false;
906 } else {
907 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
908 << " with mode " << agc_mode;
909 }
910 }
911
912 if (options.tx_agc_target_dbov.IsSet() ||
913 options.tx_agc_digital_compression_gain.IsSet() ||
914 options.tx_agc_limiter.IsSet()) {
915 // Override default_agc_config_. Generally, an unset option means "leave
916 // the VoE bits alone" in this function, so we want whatever is set to be
917 // stored as the new "default". If we didn't, then setting e.g.
918 // tx_agc_target_dbov would reset digital compression gain and limiter
919 // settings.
920 // Also, if we don't update default_agc_config_, then adjust_agc_delta
921 // would be an offset from the original values, and not whatever was set
922 // explicitly.
923 default_agc_config_.targetLeveldBOv =
924 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
925 default_agc_config_.targetLeveldBOv);
926 default_agc_config_.digitalCompressionGaindB =
927 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
928 default_agc_config_.digitalCompressionGaindB);
929 default_agc_config_.limiterEnable =
930 options.tx_agc_limiter.GetWithDefaultIfUnset(
931 default_agc_config_.limiterEnable);
932 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
933 LOG_RTCERR3(SetAgcConfig,
934 default_agc_config_.targetLeveldBOv,
935 default_agc_config_.digitalCompressionGaindB,
936 default_agc_config_.limiterEnable);
937 return false;
938 }
939 }
940
941 bool noise_suppression;
942 if (options.noise_suppression.Get(&noise_suppression)) {
943 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
944 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
945 return false;
946 } else {
947 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
948 << " with mode " << ns_mode;
949 }
950 }
951
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000952 bool highpass_filter;
953 if (options.highpass_filter.Get(&highpass_filter)) {
954 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
955 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
956 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
957 return false;
958 }
959 }
960
961 bool stereo_swapping;
962 if (options.stereo_swapping.Get(&stereo_swapping)) {
963 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
964 voep->EnableStereoChannelSwapping(stereo_swapping);
965 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
966 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
967 return false;
968 }
969 }
970
971 bool typing_detection;
972 if (options.typing_detection.Get(&typing_detection)) {
973 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
974 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
975 // In case of error, log the info and continue
976 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
977 }
978 }
979
980 int adjust_agc_delta;
981 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
982 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
983 if (!AdjustAgcLevel(adjust_agc_delta)) {
984 return false;
985 }
986 }
987
988 bool aec_dump;
989 if (options.aec_dump.Get(&aec_dump)) {
990 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
991 if (aec_dump)
992 StartAecDump(kAecDumpByAudioOptionFilename);
993 else
994 StopAecDump();
995 }
996
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000997 webrtc::Config config;
998
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100999 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
1000 bool delay_agnostic_aec;
1001 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
1002 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
1003 config.Set<webrtc::ReportedDelay>(
1004 new webrtc::ReportedDelay(!delay_agnostic_aec));
1005 }
1006
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001007 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001008 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001009 if (experimental_aec_.Get(&experimental_aec)) {
1010 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
1011 config.Set<webrtc::DelayCorrection>(
1012 new webrtc::DelayCorrection(experimental_aec));
1013 }
1014
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001015 experimental_ns_.SetFrom(options.experimental_ns);
1016 bool experimental_ns;
1017 if (experimental_ns_.Get(&experimental_ns)) {
1018 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
1019 config.Set<webrtc::ExperimentalNs>(
1020 new webrtc::ExperimentalNs(experimental_ns));
1021 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001022
1023 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
1024 // returns NULL on audio_processing().
1025 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
1026 if (audioproc) {
1027 audioproc->SetExtraOptions(config);
1028 }
1029
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001030 uint32 recording_sample_rate;
1031 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1032 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1033 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1034 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1035 }
1036 }
1037
1038 uint32 playout_sample_rate;
1039 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1040 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1041 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1042 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1043 }
1044 }
1045
1046 return true;
1047}
1048
1049bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1050 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1051 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1052 LOG_RTCERR1(SetDelayOffsetMs, offset);
1053 return false;
1054 }
1055
1056 return true;
1057}
1058
1059struct ResumeEntry {
1060 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1061 : channel(c),
1062 playout(p),
1063 send(s) {
1064 }
1065
1066 WebRtcVoiceMediaChannel *channel;
1067 bool playout;
1068 SendFlags send;
1069};
1070
1071// TODO(juberti): Refactor this so that the core logic can be used to set the
1072// soundclip device. At that time, reinstate the soundclip pause/resume code.
1073bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1074 const Device* out_device) {
1075#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001076 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001077 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001078 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001079 kDefaultAudioDeviceId;
1080 // The device manager uses -1 as the default device, which was the case for
1081 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1082#ifndef WIN32
1083 if (-1 == in_id) {
1084 in_id = kDefaultAudioDeviceId;
1085 }
1086 if (-1 == out_id) {
1087 out_id = kDefaultAudioDeviceId;
1088 }
1089#endif
1090
1091 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1092 in_device->name : "Default device";
1093 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1094 out_device->name : "Default device";
1095 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1096 << ") and speaker to (id=" << out_id << ", name=" << out_name
1097 << ")";
1098
1099 // If we're running the local monitor, we need to stop it first.
1100 bool ret = true;
1101 if (!PauseLocalMonitor()) {
1102 LOG(LS_WARNING) << "Failed to pause local monitor";
1103 ret = false;
1104 }
1105
1106 // Must also pause all audio playback and capture.
1107 for (ChannelList::const_iterator i = channels_.begin();
1108 i != channels_.end(); ++i) {
1109 WebRtcVoiceMediaChannel *channel = *i;
1110 if (!channel->PausePlayout()) {
1111 LOG(LS_WARNING) << "Failed to pause playout";
1112 ret = false;
1113 }
1114 if (!channel->PauseSend()) {
1115 LOG(LS_WARNING) << "Failed to pause send";
1116 ret = false;
1117 }
1118 }
1119
1120 // Find the recording device id in VoiceEngine and set recording device.
1121 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1122 ret = false;
1123 }
1124 if (ret) {
1125 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1126 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1127 ret = false;
1128 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001129 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1130 if (ap)
1131 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 }
1133
1134 // Find the playout device id in VoiceEngine and set playout device.
1135 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1136 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1137 ret = false;
1138 }
1139 if (ret) {
1140 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001141 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142 ret = false;
1143 }
1144 }
1145
1146 // Resume all audio playback and capture.
1147 for (ChannelList::const_iterator i = channels_.begin();
1148 i != channels_.end(); ++i) {
1149 WebRtcVoiceMediaChannel *channel = *i;
1150 if (!channel->ResumePlayout()) {
1151 LOG(LS_WARNING) << "Failed to resume playout";
1152 ret = false;
1153 }
1154 if (!channel->ResumeSend()) {
1155 LOG(LS_WARNING) << "Failed to resume send";
1156 ret = false;
1157 }
1158 }
1159
1160 // Resume local monitor.
1161 if (!ResumeLocalMonitor()) {
1162 LOG(LS_WARNING) << "Failed to resume local monitor";
1163 ret = false;
1164 }
1165
1166 if (ret) {
1167 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1168 << ") and speaker to (id="<< out_id << " name=" << out_name
1169 << ")";
1170 }
1171
1172 return ret;
1173#else
1174 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001175#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176}
1177
1178bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1179 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1180 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001181#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 *rtc_id = dev_id;
1183 return true;
1184#else
1185 // In Windows and Mac, we need to find the VoiceEngine device id by name
1186 // unless the input dev_id is the default device id.
1187 if (kDefaultAudioDeviceId == dev_id) {
1188 *rtc_id = dev_id;
1189 return true;
1190 }
1191
1192 // Get the number of VoiceEngine audio devices.
1193 int count = 0;
1194 if (is_input) {
1195 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1196 LOG_RTCERR0(GetNumOfRecordingDevices);
1197 return false;
1198 }
1199 } else {
1200 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1201 LOG_RTCERR0(GetNumOfPlayoutDevices);
1202 return false;
1203 }
1204 }
1205
1206 for (int i = 0; i < count; ++i) {
1207 char name[128];
1208 char guid[128];
1209 if (is_input) {
1210 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1211 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1212 } else {
1213 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1214 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1215 }
1216
1217 std::string webrtc_name(name);
1218 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1219 *rtc_id = i;
1220 return true;
1221 }
1222 }
1223 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1224 return false;
1225#endif
1226}
1227
1228bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1229 unsigned int ulevel;
1230 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1231 LOG_RTCERR1(GetSpeakerVolume, level);
1232 return false;
1233 }
1234 *level = ulevel;
1235 return true;
1236}
1237
1238bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1239 ASSERT(level >= 0 && level <= 255);
1240 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1241 LOG_RTCERR1(SetSpeakerVolume, level);
1242 return false;
1243 }
1244 return true;
1245}
1246
1247int WebRtcVoiceEngine::GetInputLevel() {
1248 unsigned int ulevel;
1249 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1250 static_cast<int>(ulevel) : -1;
1251}
1252
1253bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1254 desired_local_monitor_enable_ = enable;
1255 return ChangeLocalMonitor(desired_local_monitor_enable_);
1256}
1257
1258bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1259 // The voe file api is not available in chrome.
1260 if (!voe_wrapper_->file()) {
1261 return false;
1262 }
1263 if (enable && !monitor_) {
1264 monitor_.reset(new WebRtcMonitorStream);
1265 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1266 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1267 // Must call Stop() because there are some cases where Start will report
1268 // failure but still change the state, and if we leave VE in the on state
1269 // then it could crash later when trying to invoke methods on our monitor.
1270 voe_wrapper_->file()->StopRecordingMicrophone();
1271 monitor_.reset();
1272 return false;
1273 }
1274 } else if (!enable && monitor_) {
1275 voe_wrapper_->file()->StopRecordingMicrophone();
1276 monitor_.reset();
1277 }
1278 return true;
1279}
1280
1281bool WebRtcVoiceEngine::PauseLocalMonitor() {
1282 return ChangeLocalMonitor(false);
1283}
1284
1285bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1286 return ChangeLocalMonitor(desired_local_monitor_enable_);
1287}
1288
1289const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1290 return codecs_;
1291}
1292
1293bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1294 return FindWebRtcCodec(in, NULL);
1295}
1296
1297// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1298bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1299 webrtc::CodecInst* out) {
1300 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1301 for (int i = 0; i < ncodecs; ++i) {
1302 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001303 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1305 voe_codec.rate, voe_codec.channels, 0);
1306 bool multi_rate = IsCodecMultiRate(voe_codec);
1307 // Allow arbitrary rates for ISAC to be specified.
1308 if (multi_rate) {
1309 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1310 codec.bitrate = 0;
1311 }
1312 if (codec.Matches(in)) {
1313 if (out) {
1314 // Fixup the payload type.
1315 voe_codec.pltype = in.id;
1316
1317 // Set bitrate if specified.
1318 if (multi_rate && in.bitrate != 0) {
1319 voe_codec.rate = in.bitrate;
1320 }
1321
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001322 // Reset G722 sample rate to 16000 to match WebRTC.
1323 MaybeFixupG722(&voe_codec, 16000);
1324
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 // Apply codec-specific settings.
1326 if (IsIsac(codec)) {
1327 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001328 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1330 }
1331 *out = voe_codec;
1332 }
1333 return true;
1334 }
1335 }
1336 }
1337 return false;
1338}
1339const std::vector<RtpHeaderExtension>&
1340WebRtcVoiceEngine::rtp_header_extensions() const {
1341 return rtp_header_extensions_;
1342}
1343
1344void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1345 // if min_sev == -1, we keep the current log level.
1346 if (min_sev >= 0) {
1347 SetTraceFilter(SeverityToFilter(min_sev));
1348 }
1349 log_options_ = filter;
1350 SetTraceOptions(initialized_ ? log_options_ : "");
1351}
1352
1353int WebRtcVoiceEngine::GetLastEngineError() {
1354 return voe_wrapper_->error();
1355}
1356
1357void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1358 log_filter_ = filter;
1359 tracing_->SetTraceFilter(filter);
1360}
1361
1362// We suppport three different logging settings for VoiceEngine:
1363// 1. Observer callback that goes into talk diagnostic logfile.
1364// Use --logfile and --loglevel
1365//
1366// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1367// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1368//
1369// 3. EC log and dump for debugging QualityEngine.
1370// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1371//
1372// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1373// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1374void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1375 // Set encrypted trace file.
1376 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001377 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 std::vector<std::string>::iterator tracefile =
1379 std::find(opts.begin(), opts.end(), "tracefile");
1380 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1381 // Write encrypted debug output (at same loglevel) to file
1382 // EncryptedTraceFile no longer supported.
1383 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1384 LOG_RTCERR1(SetTraceFile, *tracefile);
1385 }
1386 }
1387
wu@webrtc.org97077a32013-10-25 21:18:33 +00001388 // Allow trace options to override the trace filter. We default
1389 // it to log_filter_ (as a translation of libjingle log levels)
1390 // elsewhere, but this allows clients to explicitly set webrtc
1391 // log levels.
1392 std::vector<std::string>::iterator tracefilter =
1393 std::find(opts.begin(), opts.end(), "tracefilter");
1394 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001395 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001396 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1397 }
1398 }
1399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 // Set AEC dump file
1401 std::vector<std::string>::iterator recordEC =
1402 std::find(opts.begin(), opts.end(), "recordEC");
1403 if (recordEC != opts.end()) {
1404 ++recordEC;
1405 if (recordEC != opts.end())
1406 StartAecDump(recordEC->c_str());
1407 else
1408 StopAecDump();
1409 }
1410}
1411
1412// Ignore spammy trace messages, mostly from the stats API when we haven't
1413// gotten RTCP info yet from the remote side.
1414bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1415 static const char* kTracesToIgnore[] = {
1416 "\tfailed to GetReportBlockInformation",
1417 "GetRecCodec() failed to get received codec",
1418 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1419 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1420 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1421 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1422 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1423 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1424 "SenderInfoReceived No received SR",
1425 "StatisticsRTP() no statistics available",
1426 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1427 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1428 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1429 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1430 NULL
1431 };
1432 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1433 if (trace.find(*p) != std::string::npos) {
1434 return true;
1435 }
1436 }
1437 return false;
1438}
1439
1440void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1441 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001442 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001444 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001448 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001450 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451
1452 // Skip past boilerplate prefix text
1453 if (length < 72) {
1454 std::string msg(trace, length);
1455 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1456 LOG_V(sev) << msg;
1457 } else {
1458 std::string msg(trace + 71, length - 72);
1459 if (!ShouldIgnoreTrace(msg)) {
1460 LOG_V(sev) << "webrtc: " << msg;
1461 }
1462 }
1463}
1464
1465void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001466 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 WebRtcVoiceMediaChannel* channel = NULL;
1468 uint32 ssrc = 0;
1469 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1470 << channel_num << ".";
1471 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1472 ASSERT(channel != NULL);
1473 channel->OnError(ssrc, err_code);
1474 } else {
1475 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1476 << " could not be found in channel list when error reported.";
1477 }
1478}
1479
1480bool WebRtcVoiceEngine::FindChannelAndSsrc(
1481 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1482 ASSERT(channel != NULL && ssrc != NULL);
1483
1484 *channel = NULL;
1485 *ssrc = 0;
1486 // Find corresponding channel and ssrc
1487 for (ChannelList::const_iterator it = channels_.begin();
1488 it != channels_.end(); ++it) {
1489 ASSERT(*it != NULL);
1490 if ((*it)->FindSsrc(channel_num, ssrc)) {
1491 *channel = *it;
1492 return true;
1493 }
1494 }
1495
1496 return false;
1497}
1498
1499// This method will search through the WebRtcVoiceMediaChannels and
1500// obtain the voice engine's channel number.
1501bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1502 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1503 ASSERT(channel_num != NULL);
1504 ASSERT(direction == MPD_RX || direction == MPD_TX);
1505
1506 *channel_num = -1;
1507 // Find corresponding channel for ssrc.
1508 for (ChannelList::const_iterator it = channels_.begin();
1509 it != channels_.end(); ++it) {
1510 ASSERT(*it != NULL);
1511 if (direction & MPD_RX) {
1512 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1513 }
1514 if (*channel_num == -1 && (direction & MPD_TX)) {
1515 *channel_num = (*it)->GetSendChannelNum(ssrc);
1516 }
1517 if (*channel_num != -1) {
1518 return true;
1519 }
1520 }
1521 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1522 return false;
1523}
1524
1525void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001526 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527 channels_.push_back(channel);
1528}
1529
1530void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001531 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532 ChannelList::iterator i = std::find(channels_.begin(),
1533 channels_.end(),
1534 channel);
1535 if (i != channels_.end()) {
1536 channels_.erase(i);
1537 }
1538}
1539
1540void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1541 soundclips_.push_back(soundclip);
1542}
1543
1544void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1545 SoundclipList::iterator i = std::find(soundclips_.begin(),
1546 soundclips_.end(),
1547 soundclip);
1548 if (i != soundclips_.end()) {
1549 soundclips_.erase(i);
1550 }
1551}
1552
1553// Adjusts the default AGC target level by the specified delta.
1554// NB: If we start messing with other config fields, we'll want
1555// to save the current webrtc::AgcConfig as well.
1556bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1557 webrtc::AgcConfig config = default_agc_config_;
1558 config.targetLeveldBOv -= delta;
1559
1560 LOG(LS_INFO) << "Adjusting AGC level from default -"
1561 << default_agc_config_.targetLeveldBOv << "dB to -"
1562 << config.targetLeveldBOv << "dB";
1563
1564 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1565 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1566 return false;
1567 }
1568 return true;
1569}
1570
1571bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1572 webrtc::AudioDeviceModule* adm_sc) {
1573 if (initialized_) {
1574 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1575 return false;
1576 }
1577 if (adm_) {
1578 adm_->Release();
1579 adm_ = NULL;
1580 }
1581 if (adm) {
1582 adm_ = adm;
1583 adm_->AddRef();
1584 }
1585
1586 if (adm_sc_) {
1587 adm_sc_->Release();
1588 adm_sc_ = NULL;
1589 }
1590 if (adm_sc) {
1591 adm_sc_ = adm_sc;
1592 adm_sc_->AddRef();
1593 }
1594 return true;
1595}
1596
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001597bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1598 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001599 if (!aec_dump_file_stream) {
1600 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001601 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001602 LOG(LS_WARNING) << "Could not close file.";
1603 return false;
1604 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001605 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001606 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001607 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001608 LOG_RTCERR0(StartDebugRecording);
1609 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001610 return false;
1611 }
1612 is_dumping_aec_ = true;
1613 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001614}
1615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616bool WebRtcVoiceEngine::RegisterProcessor(
1617 uint32 ssrc,
1618 VoiceProcessor* voice_processor,
1619 MediaProcessorDirection direction) {
1620 bool register_with_webrtc = false;
1621 int channel_id = -1;
1622 bool success = false;
1623 uint32* processor_ssrc = NULL;
1624 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1625 if (voice_processor == NULL || !found_channel) {
1626 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1627 << " foundChannel: " << found_channel;
1628 return false;
1629 }
1630
1631 webrtc::ProcessingTypes processing_type;
1632 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001633 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 if (direction == MPD_RX) {
1635 processing_type = webrtc::kPlaybackAllChannelsMixed;
1636 if (SignalRxMediaFrame.is_empty()) {
1637 register_with_webrtc = true;
1638 processor_ssrc = &rx_processor_ssrc_;
1639 }
1640 SignalRxMediaFrame.connect(voice_processor,
1641 &VoiceProcessor::OnFrame);
1642 } else {
1643 processing_type = webrtc::kRecordingPerChannel;
1644 if (SignalTxMediaFrame.is_empty()) {
1645 register_with_webrtc = true;
1646 processor_ssrc = &tx_processor_ssrc_;
1647 }
1648 SignalTxMediaFrame.connect(voice_processor,
1649 &VoiceProcessor::OnFrame);
1650 }
1651 }
1652 if (register_with_webrtc) {
1653 // TODO(janahan): when registering consider instantiating a
1654 // a VoeMediaProcess object and not make the engine extend the interface.
1655 if (voe()->media() && voe()->media()->
1656 RegisterExternalMediaProcessing(channel_id,
1657 processing_type,
1658 *this) != -1) {
1659 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1660 << channel_id;
1661 *processor_ssrc = ssrc;
1662 success = true;
1663 } else {
1664 LOG_RTCERR2(RegisterExternalMediaProcessing,
1665 channel_id,
1666 processing_type);
1667 success = false;
1668 }
1669 } else {
1670 // If we don't have to register with the engine, we just needed to
1671 // connect a new processor, set success to true;
1672 success = true;
1673 }
1674 return success;
1675}
1676
1677bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1678 MediaProcessorDirection channel_direction,
1679 uint32 ssrc,
1680 VoiceProcessor* voice_processor,
1681 MediaProcessorDirection processor_direction) {
1682 bool success = true;
1683 FrameSignal* signal;
1684 webrtc::ProcessingTypes processing_type;
1685 uint32* processor_ssrc = NULL;
1686 if (channel_direction == MPD_RX) {
1687 signal = &SignalRxMediaFrame;
1688 processing_type = webrtc::kPlaybackAllChannelsMixed;
1689 processor_ssrc = &rx_processor_ssrc_;
1690 } else {
1691 signal = &SignalTxMediaFrame;
1692 processing_type = webrtc::kRecordingPerChannel;
1693 processor_ssrc = &tx_processor_ssrc_;
1694 }
1695
1696 int deregister_id = -1;
1697 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1700 signal->disconnect(voice_processor);
1701 int channel_id = -1;
1702 bool found_channel = FindChannelNumFromSsrc(ssrc,
1703 channel_direction,
1704 &channel_id);
1705 if (signal->is_empty() && found_channel) {
1706 deregister_id = channel_id;
1707 }
1708 }
1709 }
1710 if (deregister_id != -1) {
1711 if (voe()->media() &&
1712 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1713 processing_type) != -1) {
1714 *processor_ssrc = 0;
1715 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1716 << deregister_id;
1717 } else {
1718 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1719 deregister_id,
1720 processing_type);
1721 success = false;
1722 }
1723 }
1724 return success;
1725}
1726
1727bool WebRtcVoiceEngine::UnregisterProcessor(
1728 uint32 ssrc,
1729 VoiceProcessor* voice_processor,
1730 MediaProcessorDirection direction) {
1731 bool success = true;
1732 if (voice_processor == NULL) {
1733 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1734 << ssrc;
1735 return false;
1736 }
1737 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1738 success = false;
1739 }
1740 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1741 success = false;
1742 }
1743 return success;
1744}
1745
1746// Implementing method from WebRtc VoEMediaProcess interface
1747// Do not lock mux_channel_cs_ in this callback.
1748void WebRtcVoiceEngine::Process(int channel,
1749 webrtc::ProcessingTypes type,
1750 int16_t audio10ms[],
1751 int length,
1752 int sampling_freq,
1753 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001754 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1756 if (type == webrtc::kPlaybackAllChannelsMixed) {
1757 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1758 } else if (type == webrtc::kRecordingPerChannel) {
1759 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1760 } else {
1761 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1762 << " channel: " << channel << " type: " << type
1763 << " tx_ssrc: " << tx_processor_ssrc_
1764 << " rx_ssrc: " << rx_processor_ssrc_;
1765 }
1766}
1767
1768void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1769 if (!is_dumping_aec_) {
1770 // Start dumping AEC when we are not dumping.
1771 if (voe_wrapper_->processing()->StartDebugRecording(
1772 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001773 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 } else {
1775 is_dumping_aec_ = true;
1776 }
1777 }
1778}
1779
1780void WebRtcVoiceEngine::StopAecDump() {
1781 if (is_dumping_aec_) {
1782 // Stop dumping AEC when we are dumping.
1783 if (voe_wrapper_->processing()->StopDebugRecording() !=
1784 webrtc::AudioProcessing::kNoError) {
1785 LOG_RTCERR0(StopDebugRecording);
1786 }
1787 is_dumping_aec_ = false;
1788 }
1789}
1790
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001791int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001792 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001793}
1794
1795int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1796 return CreateVoiceChannel(voe_wrapper_.get());
1797}
1798
1799int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1800 return CreateVoiceChannel(voe_wrapper_sc_.get());
1801}
1802
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001803class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1804 : public AudioRenderer::Sink {
1805 public:
1806 WebRtcVoiceChannelRenderer(int ch,
1807 webrtc::AudioTransport* voe_audio_transport)
1808 : channel_(ch),
1809 voe_audio_transport_(voe_audio_transport),
1810 renderer_(NULL) {
1811 }
1812 virtual ~WebRtcVoiceChannelRenderer() {
1813 Stop();
1814 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001815
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001816 // Starts the rendering by setting a sink to the renderer to get data
1817 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001818 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001819 // TODO(xians): Make sure Start() is called only once.
1820 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001821 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001822 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001823 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001824 ASSERT(renderer_ == renderer);
1825 return;
1826 }
1827
1828 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1829 // in getUserMedia by default.
1830 renderer->AddChannel(channel_);
1831 renderer->SetSink(this);
1832 renderer_ = renderer;
1833 }
1834
1835 // Stops rendering by setting the sink of the renderer to NULL. No data
1836 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001837 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001838 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001839 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001840 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001841 return;
1842
1843 renderer_->RemoveChannel(channel_);
1844 renderer_->SetSink(NULL);
1845 renderer_ = NULL;
1846 }
1847
1848 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001849 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001850 void OnData(const void* audio_data,
1851 int bits_per_sample,
1852 int sample_rate,
1853 int number_of_channels,
1854 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001855 voe_audio_transport_->OnData(channel_,
1856 audio_data,
1857 bits_per_sample,
1858 sample_rate,
1859 number_of_channels,
1860 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001861 }
1862
1863 // Callback from the |renderer_| when it is going away. In case Start() has
1864 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001865 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001866 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001867 // Set |renderer_| to NULL to make sure no more callback will get into
1868 // the renderer.
1869 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001870 }
1871
1872 // Accessor to the VoE channel ID.
1873 int channel() const { return channel_; }
1874
1875 private:
1876 const int channel_;
1877 webrtc::AudioTransport* const voe_audio_transport_;
1878
1879 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1880 // PeerConnection will make sure invalidating the pointer before the object
1881 // goes away.
1882 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001883
1884 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001885 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001886};
1887
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888// WebRtcVoiceMediaChannel
1889WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1890 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1891 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001892 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001893 send_bitrate_setting_(false),
1894 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895 options_(),
1896 dtmf_allowed_(false),
1897 desired_playout_(false),
1898 nack_enabled_(false),
1899 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001900 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901 desired_send_(SEND_NOTHING),
1902 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001903 shared_bwe_vie_(NULL),
1904 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 default_receive_ssrc_(0) {
1906 engine->RegisterChannel(this);
1907 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1908 << voe_channel();
1909
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001910 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911}
1912
1913WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1914 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1915 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001916 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001918 // Remove any remaining send streams, the default channel will be deleted
1919 // later.
1920 while (!send_channels_.empty())
1921 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922
1923 // Unregister ourselves from the engine.
1924 engine()->UnregisterChannel(this);
1925 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001926 while (!receive_channels_.empty()) {
1927 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 }
1929
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001930 // Delete the default channel.
1931 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932}
1933
1934bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1935 LOG(LS_INFO) << "Setting voice channel options: "
1936 << options.ToString();
1937
wu@webrtc.orgde305012013-10-31 15:40:38 +00001938 // Check if DSCP value is changed from previous.
1939 bool dscp_option_changed = (options_.dscp != options.dscp);
1940
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001941 // TODO(xians): Add support to set different options for different send
1942 // streams after we support multiple APMs.
1943
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 // We retain all of the existing options, and apply the given ones
1945 // on top. This means there is no way to "clear" options such that
1946 // they go back to the engine default.
1947 options_.SetAll(options);
1948
1949 if (send_ != SEND_NOTHING) {
1950 if (!engine()->SetOptionOverrides(options_)) {
1951 LOG(LS_WARNING) <<
1952 "Failed to engine SetOptionOverrides during channel SetOptions.";
1953 return false;
1954 }
1955 } else {
1956 // Will be interpreted when appropriate.
1957 }
1958
wu@webrtc.org97077a32013-10-25 21:18:33 +00001959 // Receiver-side auto gain control happens per channel, so set it here from
1960 // options. Note that, like conference mode, setting it on the engine won't
1961 // have the desired effect, since voice channels don't inherit options from
1962 // the media engine when those options are applied per-channel.
1963 bool rx_auto_gain_control;
1964 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1965 if (engine()->voe()->processing()->SetRxAgcStatus(
1966 voe_channel(), rx_auto_gain_control,
1967 webrtc::kAgcFixedDigital) == -1) {
1968 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1969 return false;
1970 } else {
1971 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1972 << " with mode " << webrtc::kAgcFixedDigital;
1973 }
1974 }
1975 if (options.rx_agc_target_dbov.IsSet() ||
1976 options.rx_agc_digital_compression_gain.IsSet() ||
1977 options.rx_agc_limiter.IsSet()) {
1978 webrtc::AgcConfig config;
1979 // If only some of the options are being overridden, get the current
1980 // settings for the channel and bail if they aren't available.
1981 if (!options.rx_agc_target_dbov.IsSet() ||
1982 !options.rx_agc_digital_compression_gain.IsSet() ||
1983 !options.rx_agc_limiter.IsSet()) {
1984 if (engine()->voe()->processing()->GetRxAgcConfig(
1985 voe_channel(), config) != 0) {
1986 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1987 << "channel " << voe_channel() << ". Since not all rx "
1988 << "agc options are specified, unable to safely set rx "
1989 << "agc options.";
1990 return false;
1991 }
1992 }
1993 config.targetLeveldBOv =
1994 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1995 config.targetLeveldBOv);
1996 config.digitalCompressionGaindB =
1997 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1998 config.digitalCompressionGaindB);
1999 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
2000 config.limiterEnable);
2001 if (engine()->voe()->processing()->SetRxAgcConfig(
2002 voe_channel(), config) == -1) {
2003 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
2004 config.digitalCompressionGaindB, config.limiterEnable);
2005 return false;
2006 }
2007 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002008 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002009 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002010 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002011 dscp = kAudioDscpValue;
2012 if (MediaChannel::SetDscp(dscp) != 0) {
2013 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
2014 }
2015 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00002016
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002017 // Force update of Video Engine BWE forwarding to reflect experiment setting.
2018 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
2019 shared_bwe_vie_channel_)) {
2020 return false;
2021 }
2022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 LOG(LS_INFO) << "Set voice channel options. Current options: "
2024 << options_.ToString();
2025 return true;
2026}
2027
2028bool WebRtcVoiceMediaChannel::SetRecvCodecs(
2029 const std::vector<AudioCodec>& codecs) {
2030 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 LOG(LS_INFO) << "Setting receive voice codecs:";
2032
2033 std::vector<AudioCodec> new_codecs;
2034 // Find all new codecs. We allow adding new codecs but don't allow changing
2035 // the payload type of codecs that is already configured since we might
2036 // already be receiving packets with that payload type.
2037 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002038 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 AudioCodec old_codec;
2040 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2041 if (old_codec.id != it->id) {
2042 LOG(LS_ERROR) << it->name << " payload type changed.";
2043 return false;
2044 }
2045 } else {
2046 new_codecs.push_back(*it);
2047 }
2048 }
2049 if (new_codecs.empty()) {
2050 // There are no new codecs to configure. Already configured codecs are
2051 // never removed.
2052 return true;
2053 }
2054
2055 if (playout_) {
2056 // Receive codecs can not be changed while playing. So we temporarily
2057 // pause playout.
2058 PausePlayout();
2059 }
2060
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002061 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2063 it != new_codecs.end() && ret; ++it) {
2064 webrtc::CodecInst voe_codec;
2065 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2066 LOG(LS_INFO) << ToString(*it);
2067 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002068 if (default_receive_ssrc_ == 0) {
2069 // Set the receive codecs on the default channel explicitly if the
2070 // default channel is not used by |receive_channels_|, this happens in
2071 // conference mode or in non-conference mode when there is no playout
2072 // channel.
2073 // TODO(xians): Figure out how we use the default channel in conference
2074 // mode.
2075 if (engine()->voe()->codec()->SetRecPayloadType(
2076 voe_channel(), voe_codec) == -1) {
2077 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2078 ret = false;
2079 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002080 }
2081
2082 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002083 for (ChannelMap::iterator it = receive_channels_.begin();
2084 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002086 it->second->channel(), voe_codec) == -1) {
2087 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002088 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089 ret = false;
2090 }
2091 }
2092 } else {
2093 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2094 ret = false;
2095 }
2096 }
2097 if (ret) {
2098 recv_codecs_ = codecs;
2099 }
2100
2101 if (desired_playout_ && !playout_) {
2102 ResumePlayout();
2103 }
2104 return ret;
2105}
2106
2107bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002109 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002110 engine()->voe()->codec()->SetVADStatus(channel, false);
2111 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002112 engine()->voe()->rtp()->SetREDStatus(channel, false);
2113 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114
2115 // Scan through the list to figure out the codec to use for sending, along
2116 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002117 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118 webrtc::CodecInst send_codec;
2119 memset(&send_codec, 0, sizeof(send_codec));
2120
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002121 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002122 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002123
minyue@webrtc.org26236952014-10-29 02:27:08 +00002124 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002125
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002126 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002127 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2128 it != codecs.end(); ++it) {
2129 // Ignore codecs we don't know about. The negotiation step should prevent
2130 // this, but double-check to be sure.
2131 webrtc::CodecInst voe_codec;
2132 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002133 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 continue;
2135 }
2136
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002137 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2138 // Skip telephone-event/CN codec, which will be handled later.
2139 continue;
2140 }
2141
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002142 // We'll use the first codec in the list to actually send audio data.
2143 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002144 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002145 // used is specified in params.
2146 if (IsRedCodec(it->name)) {
2147 // Parse out the RED parameters. If we fail, just ignore RED;
2148 // we don't support all possible params/usage scenarios.
2149 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2150 continue;
2151 }
2152
2153 // Enable redundant encoding of the specified codec. Treat any
2154 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002155 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2156 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2157 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002158 return false;
2159 }
2160 } else {
2161 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002162 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002163 // For Opus as the send codec, we are to enable inband FEC if requested
2164 // and set maximum playback rate.
2165 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002166 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2167 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002168 }
Brave Yao5225dd82015-03-26 07:39:19 +08002169
2170 // Set packet size if the AudioCodec param kCodecParamPTime is set.
2171 int ptime_ms = 0;
2172 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
2173 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2174 LOG(LS_WARNING) << "Failed to set packet size for codec "
2175 << send_codec.plname;
2176 return false;
2177 }
2178 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002179 }
2180 found_send_codec = true;
2181 break;
2182 }
2183
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002184 if (nack_enabled_ != nack_enabled) {
2185 SetNack(channel, nack_enabled);
2186 nack_enabled_ = nack_enabled;
2187 }
2188
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002189 if (!found_send_codec) {
2190 LOG(LS_WARNING) << "Received empty list of codecs.";
2191 return false;
2192 }
2193
2194 // Set the codec immediately, since SetVADStatus() depends on whether
2195 // the current codec is mono or stereo.
2196 if (!SetSendCodec(channel, send_codec))
2197 return false;
2198
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002199 // FEC should be enabled after SetSendCodec.
2200 if (enable_codec_fec) {
2201 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2202 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002203 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2204 // Enable codec internal FEC. Treat any failure as fatal internal error.
2205 LOG_RTCERR2(SetFECStatus, channel, true);
2206 return false;
2207 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002208 }
2209
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002210 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002211 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2212 // will be used.
2213 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002214 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002215 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002216 << " Hz on channel "
2217 << channel;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002218 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002219 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002220 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2221 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002222 }
2223
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002224 // Always update the |send_codec_| to the currently set send codec.
2225 send_codec_.reset(new webrtc::CodecInst(send_codec));
2226
minyue@webrtc.org26236952014-10-29 02:27:08 +00002227 if (send_bitrate_setting_) {
2228 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002229 }
2230
2231 // Loop through the codecs list again to config the telephone-event/CN codec.
2232 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2233 it != codecs.end(); ++it) {
2234 // Ignore codecs we don't know about. The negotiation step should prevent
2235 // this, but double-check to be sure.
2236 webrtc::CodecInst voe_codec;
2237 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2238 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2239 continue;
2240 }
2241
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002242 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2243 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002244 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002245 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2246 channel, it->id) == -1) {
2247 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2248 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002250 } else if (IsCNCodec(it->name)) {
2251 // Turn voice activity detection/comfort noise on if supported.
2252 // Set the wideband CN payload type appropriately.
2253 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 webrtc::PayloadFrequencies cn_freq;
2255 switch (it->clockrate) {
2256 case 8000:
2257 cn_freq = webrtc::kFreq8000Hz;
2258 break;
2259 case 16000:
2260 cn_freq = webrtc::kFreq16000Hz;
2261 break;
2262 case 32000:
2263 cn_freq = webrtc::kFreq32000Hz;
2264 break;
2265 default:
2266 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2267 << " not supported.";
2268 continue;
2269 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002270 // Set the CN payloadtype and the VAD status.
2271 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2272 if (cn_freq != webrtc::kFreq8000Hz) {
2273 if (engine()->voe()->codec()->SetSendCNPayloadType(
2274 channel, it->id, cn_freq) == -1) {
2275 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2276 // TODO(ajm): This failure condition will be removed from VoE.
2277 // Restore the return here when we update to a new enough webrtc.
2278 //
2279 // Not returning false because the SetSendCNPayloadType will fail if
2280 // the channel is already sending.
2281 // This can happen if the remote description is applied twice, for
2282 // example in the case of ROAP on top of JSEP, where both side will
2283 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002285 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002286 // Only turn on VAD if we have a CN payload type that matches the
2287 // clockrate for the codec we are going to use.
2288 if (it->clockrate == send_codec.plfreq) {
2289 LOG(LS_INFO) << "Enabling VAD";
2290 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2291 LOG_RTCERR2(SetVADStatus, channel, true);
2292 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293 }
2294 }
2295 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002296 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002297 return true;
2298}
2299
2300bool WebRtcVoiceMediaChannel::SetSendCodecs(
2301 const std::vector<AudioCodec>& codecs) {
2302 dtmf_allowed_ = false;
2303 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2304 it != codecs.end(); ++it) {
2305 // Find the DTMF telephone event "codec".
2306 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2307 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2308 dtmf_allowed_ = true;
2309 }
2310 }
2311
2312 // Cache the codecs in order to configure the channel created later.
2313 send_codecs_ = codecs;
2314 for (ChannelMap::iterator iter = send_channels_.begin();
2315 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002316 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002317 return false;
2318 }
2319 }
2320
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002321 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002322 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 return true;
2324}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002325
2326void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2327 bool nack_enabled) {
2328 for (ChannelMap::const_iterator it = channels.begin();
2329 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002330 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002331 }
2332}
2333
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002334void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002336 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2338 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002339 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2341 }
2342}
2343
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344bool WebRtcVoiceMediaChannel::SetSendCodec(
2345 const webrtc::CodecInst& send_codec) {
2346 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2347 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002348 for (ChannelMap::iterator iter = send_channels_.begin();
2349 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002350 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002351 return false;
2352 }
2353
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002354 return true;
2355}
2356
2357bool WebRtcVoiceMediaChannel::SetSendCodec(
2358 int channel, const webrtc::CodecInst& send_codec) {
2359 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2360 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2361
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002362 webrtc::CodecInst current_codec;
2363 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2364 (send_codec == current_codec)) {
2365 // Codec is already configured, we can return without setting it again.
2366 return true;
2367 }
2368
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002369 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2370 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 return false;
2372 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373 return true;
2374}
2375
2376bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2377 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002378 if (receive_extensions_ == extensions) {
2379 return true;
2380 }
2381
2382 // The default channel may or may not be in |receive_channels_|. Set the rtp
2383 // header extensions for default channel regardless.
2384 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2385 return false;
2386 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002387
2388 // Loop through all receive channels and enable/disable the extensions.
2389 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2390 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002391 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2392 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002393 return false;
2394 }
2395 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002396
2397 receive_extensions_ = extensions;
2398 return true;
2399}
2400
2401bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2402 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002403 const RtpHeaderExtension* audio_level_extension =
2404 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2405 if (!SetHeaderExtension(
2406 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2407 audio_level_extension)) {
2408 return false;
2409 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002410
2411 const RtpHeaderExtension* send_time_extension =
2412 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2413 if (!SetHeaderExtension(
2414 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2415 send_time_extension)) {
2416 return false;
2417 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418 return true;
2419}
2420
2421bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2422 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002423 if (send_extensions_ == extensions) {
2424 return true;
2425 }
2426
2427 // The default channel may or may not be in |send_channels_|. Set the rtp
2428 // header extensions for default channel regardless.
2429
2430 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2431 return false;
2432 }
2433
2434 // Loop through all send channels and enable/disable the extensions.
2435 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2436 channel_it != send_channels_.end(); ++channel_it) {
2437 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2438 extensions)) {
2439 return false;
2440 }
2441 }
2442
2443 send_extensions_ = extensions;
2444 return true;
2445}
2446
2447bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2448 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002449 const RtpHeaderExtension* audio_level_extension =
2450 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002451
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002452 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002453 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002454 audio_level_extension)) {
2455 return false;
2456 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002457
2458 const RtpHeaderExtension* send_time_extension =
2459 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002460 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002461 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002462 send_time_extension)) {
2463 return false;
2464 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 return true;
2467}
2468
2469bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2470 desired_playout_ = playout;
2471 return ChangePlayout(desired_playout_);
2472}
2473
2474bool WebRtcVoiceMediaChannel::PausePlayout() {
2475 return ChangePlayout(false);
2476}
2477
2478bool WebRtcVoiceMediaChannel::ResumePlayout() {
2479 return ChangePlayout(desired_playout_);
2480}
2481
2482bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2483 if (playout_ == playout) {
2484 return true;
2485 }
2486
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002487 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002488 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002489 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 // Only toggle the default channel if we don't have any other channels.
2491 result = SetPlayout(voe_channel(), playout);
2492 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002493 for (ChannelMap::iterator it = receive_channels_.begin();
2494 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002495 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002496 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002497 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 result = false;
2499 }
2500 }
2501
2502 if (result) {
2503 playout_ = playout;
2504 }
2505 return result;
2506}
2507
2508bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2509 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002510 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002511 return ChangeSend(desired_send_);
2512 return true;
2513}
2514
2515bool WebRtcVoiceMediaChannel::PauseSend() {
2516 return ChangeSend(SEND_NOTHING);
2517}
2518
2519bool WebRtcVoiceMediaChannel::ResumeSend() {
2520 return ChangeSend(desired_send_);
2521}
2522
2523bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2524 if (send_ == send) {
2525 return true;
2526 }
2527
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002528 // Change the settings on each send channel.
2529 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002530 engine()->SetOptionOverrides(options_);
2531
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002532 // Change the settings on each send channel.
2533 for (ChannelMap::iterator iter = send_channels_.begin();
2534 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002535 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002538
2539 // Clear up the options after stopping sending.
2540 if (send == SEND_NOTHING)
2541 engine()->ClearOptionOverrides();
2542
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543 send_ = send;
2544 return true;
2545}
2546
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002547bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2548 if (send == SEND_MICROPHONE) {
2549 if (engine()->voe()->base()->StartSend(channel) == -1) {
2550 LOG_RTCERR1(StartSend, channel);
2551 return false;
2552 }
2553 if (engine()->voe()->file() &&
2554 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2555 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2556 return false;
2557 }
2558 } else { // SEND_NOTHING
2559 ASSERT(send == SEND_NOTHING);
2560 if (engine()->voe()->base()->StopSend(channel) == -1) {
2561 LOG_RTCERR1(StopSend, channel);
2562 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563 }
2564 }
2565
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566 return true;
2567}
2568
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002569// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002570void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2571 if (engine()->voe()->network()->RegisterExternalTransport(
2572 channel, *this) == -1) {
2573 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2574 }
2575
2576 // Enable RTCP (for quality stats and feedback messages)
2577 EnableRtcp(channel);
2578
2579 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2580 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002581
2582 // Set RTP header extension for the new channel.
2583 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002584}
2585
2586bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2587 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2588 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2589 }
2590
2591 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2592 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return false;
2594 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002595
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002596 return true;
2597}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002598
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002599bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2600 // If the default channel is already used for sending create a new channel
2601 // otherwise use the default channel for sending.
2602 int channel = GetSendChannelNum(sp.first_ssrc());
2603 if (channel != -1) {
2604 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2605 return false;
2606 }
2607
2608 bool default_channel_is_available = true;
2609 for (ChannelMap::const_iterator iter = send_channels_.begin();
2610 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002611 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002612 default_channel_is_available = false;
2613 break;
2614 }
2615 }
2616 if (default_channel_is_available) {
2617 channel = voe_channel();
2618 } else {
2619 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002620 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002621 if (channel == -1) {
2622 LOG_RTCERR0(CreateChannel);
2623 return false;
2624 }
2625
2626 ConfigureSendChannel(channel);
2627 }
2628
2629 // Save the channel to send_channels_, so that RemoveSendStream() can still
2630 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002631 webrtc::AudioTransport* audio_transport =
2632 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002633 send_channels_.insert(std::make_pair(
2634 sp.first_ssrc(),
2635 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002636
2637 // Set the send (local) SSRC.
2638 // If there are multiple send SSRCs, we can only set the first one here, and
2639 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2640 // (with a codec requires multiple SSRC(s)).
2641 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2642 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2643 return false;
2644 }
2645
2646 // At this point the channel's local SSRC has been updated. If the channel is
2647 // the default channel make sure that all the receive channels are updated as
2648 // well. Receive channels have to have the same SSRC as the default channel in
2649 // order to send receiver reports with this SSRC.
2650 if (IsDefaultChannel(channel)) {
2651 for (ChannelMap::const_iterator it = receive_channels_.begin();
2652 it != receive_channels_.end(); ++it) {
2653 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002654 if (!IsDefaultChannel(it->second->channel())) {
2655 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002656 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002657 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002658 return false;
2659 }
2660 }
2661 }
2662 }
2663
2664 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002665 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2666 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002667 }
2668
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002669 // Set the current codecs to be used for the new channel.
2670 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002671 return false;
2672
2673 return ChangeSend(channel, desired_send_);
2674}
2675
2676bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2677 ChannelMap::iterator it = send_channels_.find(ssrc);
2678 if (it == send_channels_.end()) {
2679 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2680 << " which doesn't exist.";
2681 return false;
2682 }
2683
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002684 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002685 ChangeSend(channel, SEND_NOTHING);
2686
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002687 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2688 // this will disconnect the audio renderer with the send channel.
2689 delete it->second;
2690 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002691
2692 if (IsDefaultChannel(channel)) {
2693 // Do not delete the default channel since the receive channels depend on
2694 // the default channel, recycle it instead.
2695 ChangeSend(channel, SEND_NOTHING);
2696 } else {
2697 // Clean up and delete the send channel.
2698 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2699 << " with VoiceEngine channel #" << channel << ".";
2700 if (!DeleteChannel(channel))
2701 return false;
2702 }
2703
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002704 if (send_channels_.empty())
2705 ChangeSend(SEND_NOTHING);
2706
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707 return true;
2708}
2709
2710bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002711 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712
2713 if (!VERIFY(sp.ssrcs.size() == 1))
2714 return false;
2715 uint32 ssrc = sp.first_ssrc();
2716
wu@webrtc.org78187522013-10-07 23:32:02 +00002717 if (ssrc == 0) {
2718 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2719 return false;
2720 }
2721
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2723 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002724 return false;
2725 }
2726
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002727 // Reuse default channel for recv stream in non-conference mode call
2728 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002729 webrtc::AudioTransport* audio_transport =
2730 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002731 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2732 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2733 << " reuse default channel";
2734 default_receive_ssrc_ = sp.first_ssrc();
2735 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002736 default_receive_ssrc_,
2737 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002738 if (!SetupSharedBweOnChannel(voe_channel())) {
2739 return false;
2740 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 return SetPlayout(voe_channel(), playout_);
2742 }
2743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002745 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746 if (channel == -1) {
2747 LOG_RTCERR0(CreateChannel);
2748 return false;
2749 }
2750
wu@webrtc.org78187522013-10-07 23:32:02 +00002751 if (!ConfigureRecvChannel(channel)) {
2752 DeleteChannel(channel);
2753 return false;
2754 }
2755
2756 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002757 std::make_pair(
2758 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002759
2760 LOG(LS_INFO) << "New audio stream " << ssrc
2761 << " registered to VoiceEngine channel #"
2762 << channel << ".";
2763 return true;
2764}
2765
2766bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767 // Configure to use external transport, like our default channel.
2768 if (engine()->voe()->network()->RegisterExternalTransport(
2769 channel, *this) == -1) {
2770 LOG_RTCERR2(SetExternalTransport, channel, this);
2771 return false;
2772 }
2773
2774 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002775 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2777 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002778 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 return false;
2780 }
2781 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002782 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002783 return false;
2784 }
2785
2786 // Use the same recv payload types as our default channel.
2787 ResetRecvCodecs(channel);
2788 if (!recv_codecs_.empty()) {
2789 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2790 it != recv_codecs_.end(); ++it) {
2791 webrtc::CodecInst voe_codec;
2792 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2793 voe_codec.pltype = it->id;
2794 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2795 if (engine()->voe()->codec()->GetRecPayloadType(
2796 voe_channel(), voe_codec) != -1) {
2797 if (engine()->voe()->codec()->SetRecPayloadType(
2798 channel, voe_codec) == -1) {
2799 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2800 return false;
2801 }
2802 }
2803 }
2804 }
2805 }
2806
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002807 if (InConferenceMode()) {
2808 // To be in par with the video, voe_channel() is not used for receiving in
2809 // a conference call.
2810 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2811 // This is the first stream in a multi user meeting. We can now
2812 // disable playback of the default stream. This since the default
2813 // stream will probably have received some initial packets before
2814 // the new stream was added. This will mean that the CN state from
2815 // the default channel will be mixed in with the other streams
2816 // throughout the whole meeting, which might be disturbing.
2817 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2818 SetPlayout(voe_channel(), false);
2819 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002821 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002823 // Set RTP header extension for the new channel.
2824 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2825 return false;
2826 }
2827
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002828 // Set up channel to be able to forward incoming packets to video engine BWE.
2829 if (!SetupSharedBweOnChannel(channel)) {
2830 return false;
2831 }
2832
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833 return SetPlayout(channel, playout_);
2834}
2835
2836bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002837 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002838 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002839 if (it == receive_channels_.end()) {
2840 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2841 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002843 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002845 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2846 // will disconnect the audio renderer with the receive channel.
2847 // Cache the channel before the deletion.
2848 const int channel = it->second->channel();
2849 delete it->second;
2850 receive_channels_.erase(it);
2851
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002853 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002854 // Recycle the default channel is for recv stream.
2855 if (playout_)
2856 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002858 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002859 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002860 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002861
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002862 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002863 << " with VoiceEngine channel #" << channel << ".";
2864 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002865 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002866
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002867 bool enable_default_channel_playout = false;
2868 if (receive_channels_.empty()) {
2869 // The last stream was removed. We can now enable the default
2870 // channel for new channels to be played out immediately without
2871 // waiting for AddStream messages.
2872 // We do this for both conference mode and non-conference mode.
2873 // TODO(oja): Does the default channel still have it's CN state?
2874 enable_default_channel_playout = true;
2875 }
2876 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2877 default_receive_ssrc_ != 0) {
2878 // Only the default channel is active, enable the playout on default
2879 // channel.
2880 enable_default_channel_playout = true;
2881 }
2882 if (enable_default_channel_playout && playout_) {
2883 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2884 SetPlayout(voe_channel(), true);
2885 }
2886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002887 return true;
2888}
2889
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002890bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2891 AudioRenderer* renderer) {
2892 ChannelMap::iterator it = receive_channels_.find(ssrc);
2893 if (it == receive_channels_.end()) {
2894 if (renderer) {
2895 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002896 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002897 return false;
2898 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002900 // The channel likely has gone away, do nothing.
2901 return true;
2902 }
2903
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002904 if (renderer)
2905 it->second->Start(renderer);
2906 else
2907 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002908
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002909 return true;
2910}
2911
2912bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2913 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002914 ChannelMap::iterator it = send_channels_.find(ssrc);
2915 if (it == send_channels_.end()) {
2916 if (renderer) {
2917 // Return an error if trying to set a valid renderer with an invalid ssrc.
2918 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2919 return false;
2920 }
2921
2922 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002923 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002924 }
2925
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002926 if (renderer)
2927 it->second->Start(renderer);
2928 else
2929 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002930
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931 return true;
2932}
2933
2934bool WebRtcVoiceMediaChannel::GetActiveStreams(
2935 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002936 // In conference mode, the default channel should not be in
2937 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002939 for (ChannelMap::iterator it = receive_channels_.begin();
2940 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002941 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942 if (level > 0) {
2943 actives->push_back(std::make_pair(it->first, level));
2944 }
2945 }
2946 return true;
2947}
2948
2949int WebRtcVoiceMediaChannel::GetOutputLevel() {
2950 // return the highest output level of all streams
2951 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002952 for (ChannelMap::iterator it = receive_channels_.begin();
2953 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002954 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002955 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 }
2957 return highest;
2958}
2959
2960int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2961 int ret;
2962 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2963 // In case of error, log the info and continue
2964 LOG_RTCERR0(TimeSinceLastTyping);
2965 ret = -1;
2966 } else {
2967 ret *= 1000; // We return ms, webrtc returns seconds.
2968 }
2969 return ret;
2970}
2971
2972void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2973 int cost_per_typing, int reporting_threshold, int penalty_decay,
2974 int type_event_delay) {
2975 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2976 time_window, cost_per_typing,
2977 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2978 // In case of error, log the info and continue
2979 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2980 cost_per_typing, reporting_threshold, penalty_decay,
2981 type_event_delay);
2982 }
2983}
2984
2985bool WebRtcVoiceMediaChannel::SetOutputScaling(
2986 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002987 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 // Collect the channels to scale the output volume.
2989 std::vector<int> channels;
2990 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002991 // Default channel is not in receive_channels_ if it is not being used for
2992 // playout.
2993 if (default_receive_ssrc_ == 0)
2994 channels.push_back(voe_channel());
2995 for (ChannelMap::const_iterator it = receive_channels_.begin();
2996 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002997 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 }
2999 } else { // Collect only the channel of the specified ssrc.
3000 int channel = GetReceiveChannelNum(ssrc);
3001 if (-1 == channel) {
3002 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3003 return false;
3004 }
3005 channels.push_back(channel);
3006 }
3007
3008 // Scale the output volume for the collected channels. We first normalize to
3009 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00003010 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003011 if (scale > 0.0001f) {
3012 left /= scale;
3013 right /= scale;
3014 }
3015 for (std::vector<int>::const_iterator it = channels.begin();
3016 it != channels.end(); ++it) {
3017 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
3018 *it, scale)) {
3019 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
3020 return false;
3021 }
3022 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
3023 *it, static_cast<float>(left), static_cast<float>(right))) {
3024 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
3025 // Do not return if fails. SetOutputVolumePan is not available for all
3026 // pltforms.
3027 }
3028 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
3029 << " right=" << right * scale
3030 << " for channel " << *it << " and ssrc " << ssrc;
3031 }
3032 return true;
3033}
3034
3035bool WebRtcVoiceMediaChannel::GetOutputScaling(
3036 uint32 ssrc, double* left, double* right) {
3037 if (!left || !right) return false;
3038
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003039 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003040 // Determine which channel based on ssrc.
3041 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3042 if (channel == -1) {
3043 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3044 return false;
3045 }
3046
3047 float scaling;
3048 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3049 channel, scaling)) {
3050 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3051 return false;
3052 }
3053
3054 float left_pan;
3055 float right_pan;
3056 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3057 channel, left_pan, right_pan)) {
3058 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3059 // If GetOutputVolumePan fails, we use the default left and right pan.
3060 left_pan = 1.0f;
3061 right_pan = 1.0f;
3062 }
3063
3064 *left = scaling * left_pan;
3065 *right = scaling * right_pan;
3066 return true;
3067}
3068
3069bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3070 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3071 return true;
3072}
3073
3074bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3075 bool play, bool loop) {
3076 if (!ringback_tone_) {
3077 return false;
3078 }
3079
3080 // The voe file api is not available in chrome.
3081 if (!engine()->voe()->file()) {
3082 return false;
3083 }
3084
3085 // Determine which VoiceEngine channel to play on.
3086 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3087 if (channel == -1) {
3088 return false;
3089 }
3090
3091 // Make sure the ringtone is cued properly, and play it out.
3092 if (play) {
3093 ringback_tone_->set_loop(loop);
3094 ringback_tone_->Rewind();
3095 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3096 ringback_tone_.get()) == -1) {
3097 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3098 LOG(LS_ERROR) << "Unable to start ringback tone";
3099 return false;
3100 }
3101 ringback_channels_.insert(channel);
3102 LOG(LS_INFO) << "Started ringback on channel " << channel;
3103 } else {
3104 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3105 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3106 LOG_RTCERR1(StopPlayingFileLocally, channel);
3107 return false;
3108 }
3109 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3110 ringback_channels_.erase(channel);
3111 }
3112
3113 return true;
3114}
3115
3116bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3117 return dtmf_allowed_;
3118}
3119
3120bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3121 int duration, int flags) {
3122 if (!dtmf_allowed_) {
3123 return false;
3124 }
3125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003126 // Send the event.
3127 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003128 int channel = -1;
3129 if (ssrc == 0) {
3130 bool default_channel_is_inuse = false;
3131 for (ChannelMap::const_iterator iter = send_channels_.begin();
3132 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003133 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003134 default_channel_is_inuse = true;
3135 break;
3136 }
3137 }
3138 if (default_channel_is_inuse) {
3139 channel = voe_channel();
3140 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003141 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003142 }
3143 } else {
3144 channel = GetSendChannelNum(ssrc);
3145 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003146 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003147 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3148 << ssrc << " is not in use.";
3149 return false;
3150 }
3151 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003152 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3153 channel, event, true, duration) == -1) {
3154 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003155 return false;
3156 }
3157 }
3158
3159 // Play the event.
3160 if (flags & cricket::DF_PLAY) {
3161 // Play DTMF tone locally.
3162 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3163 LOG_RTCERR2(PlayDtmfTone, event, duration);
3164 return false;
3165 }
3166 }
3167
3168 return true;
3169}
3170
wu@webrtc.orga9890802013-12-13 00:21:03 +00003171void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003172 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003173 // Pick which channel to send this packet to. If this packet doesn't match
3174 // any multiplexed streams, just send it to the default channel. Otherwise,
3175 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003176 int which_channel =
3177 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178 if (which_channel == -1) {
3179 which_channel = voe_channel();
3180 }
3181
3182 // Stop any ringback that might be playing on the channel.
3183 // It's possible the ringback has already stopped, ih which case we'll just
3184 // use the opportunity to remove the channel from ringback_channels_.
3185 if (engine()->voe()->file()) {
3186 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3187 if (it != ringback_channels_.end()) {
3188 if (engine()->voe()->file()->IsPlayingFileLocally(
3189 which_channel) == 1) {
3190 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3191 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3192 << " due to incoming media";
3193 }
3194 ringback_channels_.erase(which_channel);
3195 }
3196 }
3197
3198 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003199 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003200 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003201 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202}
3203
wu@webrtc.orga9890802013-12-13 00:21:03 +00003204void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003205 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003206 // Sending channels need all RTCP packets with feedback information.
3207 // Even sender reports can contain attached report blocks.
3208 // Receiving channels need sender reports in order to create
3209 // correct receiver reports.
3210 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003211 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003212 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3213 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214 }
3215
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003216 // If it is a sender report, find the channel that is listening.
3217 bool has_sent_to_default_channel = false;
3218 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003219 int which_channel =
3220 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003221 if (which_channel != -1) {
3222 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003223 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003224
3225 if (IsDefaultChannel(which_channel))
3226 has_sent_to_default_channel = true;
3227 }
3228 }
3229
3230 // SR may continue RR and any RR entry may correspond to any one of the send
3231 // channels. So all RTCP packets must be forwarded all send channels. VoE
3232 // will filter out RR internally.
3233 for (ChannelMap::iterator iter = send_channels_.begin();
3234 iter != send_channels_.end(); ++iter) {
3235 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003236 if (IsDefaultChannel(iter->second->channel()) &&
3237 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003238 continue;
3239
3240 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003241 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243}
3244
3245bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003246 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3247 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3249 return false;
3250 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003251 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3252 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 return false;
3254 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003255 // We set the AGC to mute state only when all the channels are muted.
3256 // This implementation is not ideal, instead we should signal the AGC when
3257 // the mic channel is muted/unmuted. We can't do it today because there
3258 // is no good way to know which stream is mapping to the mic channel.
3259 bool all_muted = muted;
3260 for (ChannelMap::const_iterator iter = send_channels_.begin();
3261 iter != send_channels_.end() && all_muted; ++iter) {
3262 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3263 all_muted)) {
3264 LOG_RTCERR1(GetInputMute, iter->second->channel());
3265 return false;
3266 }
3267 }
3268
3269 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3270 if (ap)
3271 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003272 return true;
3273}
3274
minyue@webrtc.org26236952014-10-29 02:27:08 +00003275// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3276// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003277bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003278 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003279
minyue@webrtc.org26236952014-10-29 02:27:08 +00003280 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003281}
3282
minyue@webrtc.org26236952014-10-29 02:27:08 +00003283bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3284 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003285
minyue@webrtc.org26236952014-10-29 02:27:08 +00003286 send_bitrate_setting_ = true;
3287 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003290 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003291 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003292 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003293 }
3294
minyue@webrtc.org26236952014-10-29 02:27:08 +00003295 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003296 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3297 // SetMaxSendBandwith(0), the second call removes the previous limit.
3298 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 return true;
3300
3301 webrtc::CodecInst codec = *send_codec_;
3302 bool is_multi_rate = IsCodecMultiRate(codec);
3303
3304 if (is_multi_rate) {
3305 // If codec is multi-rate then just set the bitrate.
3306 codec.rate = bps;
3307 if (!SetSendCodec(codec)) {
3308 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3309 << " to bitrate " << bps << " bps.";
3310 return false;
3311 }
3312 return true;
3313 } else {
3314 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3315 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3316 // fixed bitrate then ignore.
3317 if (bps < codec.rate) {
3318 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3319 << " to bitrate " << bps << " bps"
3320 << ", requires at least " << codec.rate << " bps.";
3321 return false;
3322 }
3323 return true;
3324 }
3325}
3326
3327bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003328 bool echo_metrics_on = false;
3329 // These can take on valid negative values, so use the lowest possible level
3330 // as default rather than -1.
3331 int echo_return_loss = -100;
3332 int echo_return_loss_enhancement = -100;
3333 // These can also be negative, but in practice -1 is only used to signal
3334 // insufficient data, since the resolution is limited to multiples of 4 ms.
3335 int echo_delay_median_ms = -1;
3336 int echo_delay_std_ms = -1;
3337 if (engine()->voe()->processing()->GetEcMetricsStatus(
3338 echo_metrics_on) != -1 && echo_metrics_on) {
3339 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3340 // here, but it appears to be unsuitable currently. Revisit after this is
3341 // investigated: http://b/issue?id=5666755
3342 int erl, erle, rerl, anlp;
3343 if (engine()->voe()->processing()->GetEchoMetrics(
3344 erl, erle, rerl, anlp) != -1) {
3345 echo_return_loss = erl;
3346 echo_return_loss_enhancement = erle;
3347 }
3348
3349 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003350 float dummy;
3351 if (engine()->voe()->processing()->GetEcDelayMetrics(
3352 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003353 echo_delay_median_ms = median;
3354 echo_delay_std_ms = std;
3355 }
3356 }
3357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358 webrtc::CallStatistics cs;
3359 unsigned int ssrc;
3360 webrtc::CodecInst codec;
3361 unsigned int level;
3362
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003363 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3364 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003365 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003366
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003367 // Fill in the sender info, based on what we know, and what the
3368 // remote side told us it got from its RTCP report.
3369 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003371 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3372 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3373 continue;
3374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003376 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003377 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3378 sinfo.bytes_sent = cs.bytesSent;
3379 sinfo.packets_sent = cs.packetsSent;
3380 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3381 // returns 0 to indicate an error value.
3382 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3383
3384 // Get data from the last remote RTCP report. Use default values if no data
3385 // available.
3386 sinfo.fraction_lost = -1.0;
3387 sinfo.jitter_ms = -1;
3388 sinfo.packets_lost = -1;
3389 sinfo.ext_seqnum = -1;
3390 std::vector<webrtc::ReportBlock> receive_blocks;
3391 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3392 channel, &receive_blocks) != -1 &&
3393 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3394 std::vector<webrtc::ReportBlock>::iterator iter;
3395 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3396 ++iter) {
3397 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003398 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003399 // Convert Q8 to floating point.
3400 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3401 // Convert samples to milliseconds.
3402 if (codec.plfreq / 1000 > 0) {
3403 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3404 }
3405 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3406 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3407 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003409 }
3410 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003411
3412 // Local speech level.
3413 sinfo.audio_level = (engine()->voe()->volume()->
3414 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3415
3416 // TODO(xians): We are injecting the same APM logging to all the send
3417 // channels here because there is no good way to know which send channel
3418 // is using the APM. The correct fix is to allow the send channels to have
3419 // their own APM so that we can feed the correct APM logging to different
3420 // send channels. See issue crbug/264611 .
3421 sinfo.echo_return_loss = echo_return_loss;
3422 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3423 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3424 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003425 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3426 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003427 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003428
3429 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003430 }
3431
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003432 // Build the list of receivers, one for each receiving channel, or 1 in
3433 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003435 for (ChannelMap::const_iterator it = receive_channels_.begin();
3436 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003437 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 }
3439 if (channels.empty()) {
3440 channels.push_back(voe_channel());
3441 }
3442
3443 // Get the SSRC and stats for each receiver, based on our own calculations.
3444 for (std::vector<int>::const_iterator it = channels.begin();
3445 it != channels.end(); ++it) {
3446 memset(&cs, 0, sizeof(cs));
3447 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3448 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3449 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3450 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003451 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003452 rinfo.bytes_rcvd = cs.bytesReceived;
3453 rinfo.packets_rcvd = cs.packetsReceived;
3454 // The next four fields are from the most recently sent RTCP report.
3455 // Convert Q8 to floating point.
3456 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3457 rinfo.packets_lost = cs.cumulativeLost;
3458 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003459 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003460 if (codec.pltype != -1) {
3461 rinfo.codec_name = codec.plname;
3462 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003463 // Convert samples to milliseconds.
3464 if (codec.plfreq / 1000 > 0) {
3465 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3466 }
3467
3468 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3469 webrtc::NetworkStatistics ns;
3470 if (engine()->voe()->neteq() &&
3471 engine()->voe()->neteq()->GetNetworkStatistics(
3472 *it, ns) != -1) {
3473 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3474 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3475 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003476 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003477 rinfo.speech_expand_rate =
3478 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3479 rinfo.secondary_decoded_rate =
3480 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003482
3483 webrtc::AudioDecodingCallStats ds;
3484 if (engine()->voe()->neteq() &&
3485 engine()->voe()->neteq()->GetDecodingCallStatistics(
3486 *it, &ds) != -1) {
3487 rinfo.decoding_calls_to_silence_generator =
3488 ds.calls_to_silence_generator;
3489 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3490 rinfo.decoding_normal = ds.decoded_normal;
3491 rinfo.decoding_plc = ds.decoded_plc;
3492 rinfo.decoding_cng = ds.decoded_cng;
3493 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3494 }
3495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003497 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498 int playout_buffer_delay_ms = 0;
3499 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003500 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3501 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3502 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003503 }
3504
3505 // Get speech level.
3506 rinfo.audio_level = (engine()->voe()->volume()->
3507 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3508 info->receivers.push_back(rinfo);
3509 }
3510 }
3511
3512 return true;
3513}
3514
3515void WebRtcVoiceMediaChannel::GetLastMediaError(
3516 uint32* ssrc, VoiceMediaChannel::Error* error) {
3517 ASSERT(ssrc != NULL);
3518 ASSERT(error != NULL);
3519 FindSsrc(voe_channel(), ssrc);
3520 *error = WebRtcErrorToChannelError(GetLastEngineError());
3521}
3522
3523bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003524 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003525 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003526 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003527 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3528 // This means the error is not limited to a specific channel. Signal the
3529 // message using ssrc=0. If the current channel is sending, use this
3530 // channel for sending the message.
3531 *ssrc = 0;
3532 return true;
3533 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003534 // Check whether this is a sending channel.
3535 for (ChannelMap::const_iterator it = send_channels_.begin();
3536 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003537 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003538 // This is a sending channel.
3539 uint32 local_ssrc = 0;
3540 if (engine()->voe()->rtp()->GetLocalSSRC(
3541 channel_num, local_ssrc) != -1) {
3542 *ssrc = local_ssrc;
3543 }
3544 return true;
3545 }
3546 }
3547
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003549 for (ChannelMap::const_iterator it = receive_channels_.begin();
3550 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003551 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003552 *ssrc = it->first;
3553 return true;
3554 }
3555 }
3556 }
3557 return false;
3558}
3559
3560void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003561 if (error == VE_TYPING_NOISE_WARNING) {
3562 typing_noise_detected_ = true;
3563 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3564 typing_noise_detected_ = false;
3565 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003566 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3567}
3568
3569int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3570 unsigned int ulevel;
3571 int ret =
3572 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3573 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3574}
3575
3576int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003577 ChannelMap::iterator it = receive_channels_.find(ssrc);
3578 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003579 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003580 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3581}
3582
3583int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003584 ChannelMap::iterator it = send_channels_.find(ssrc);
3585 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003586 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003587
3588 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003589}
3590
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003591bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3592 webrtc::VideoEngine* vie, int vie_channel) {
3593 shared_bwe_vie_ = vie;
3594 shared_bwe_vie_channel_ = vie_channel;
3595
3596 if (!SetupSharedBweOnChannel(voe_channel())) {
3597 return false;
3598 }
3599 for (ChannelMap::iterator it = receive_channels_.begin();
3600 it != receive_channels_.end(); ++it) {
3601 if (!SetupSharedBweOnChannel(it->second->channel())) {
3602 return false;
3603 }
3604 }
3605 return true;
3606}
3607
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003608bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3609 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3610 // Get the RED encodings from the parameter with no name. This may
3611 // change based on what is discussed on the Jingle list.
3612 // The encoding parameter is of the form "a/b"; we only support where
3613 // a == b. Verify this and parse out the value into red_pt.
3614 // If the parameter value is absent (as it will be until we wire up the
3615 // signaling of this message), use the second codec specified (i.e. the
3616 // one after "red") as the encoding parameter.
3617 int red_pt = -1;
3618 std::string red_params;
3619 CodecParameterMap::const_iterator it = red_codec.params.find("");
3620 if (it != red_codec.params.end()) {
3621 red_params = it->second;
3622 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003623 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003624 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003625 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003626 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3627 return false;
3628 }
3629 } else if (red_codec.params.empty()) {
3630 LOG(LS_WARNING) << "RED params not present, using defaults";
3631 if (all_codecs.size() > 1) {
3632 red_pt = all_codecs[1].id;
3633 }
3634 }
3635
3636 // Try to find red_pt in |codecs|.
3637 std::vector<AudioCodec>::const_iterator codec;
3638 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3639 if (codec->id == red_pt)
3640 break;
3641 }
3642
3643 // If we find the right codec, that will be the codec we pass to
3644 // SetSendCodec, with the desired payload type.
3645 if (codec != all_codecs.end() &&
3646 engine()->FindWebRtcCodec(*codec, send_codec)) {
3647 } else {
3648 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3649 return false;
3650 }
3651
3652 return true;
3653}
3654
3655bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3656 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003657 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003658 return false;
3659 }
3660 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3661 // what we want to do with them.
3662 // engine()->voe().EnableVQMon(voe_channel(), true);
3663 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3664 return true;
3665}
3666
3667bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3668 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3669 for (int i = 0; i < ncodecs; ++i) {
3670 webrtc::CodecInst voe_codec;
3671 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3672 voe_codec.pltype = -1;
3673 if (engine()->voe()->codec()->SetRecPayloadType(
3674 channel, voe_codec) == -1) {
3675 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3676 return false;
3677 }
3678 }
3679 }
3680 return true;
3681}
3682
3683bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3684 if (playout) {
3685 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3686 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3687 LOG_RTCERR1(StartPlayout, channel);
3688 return false;
3689 }
3690 } else {
3691 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3692 engine()->voe()->base()->StopPlayout(channel);
3693 }
3694 return true;
3695}
3696
3697uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3698 bool rtcp) {
3699 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3700 uint32 ssrc = 0;
3701 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003702 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003703 }
3704 return ssrc;
3705}
3706
3707// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3708VoiceMediaChannel::Error
3709 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3710 switch (err_code) {
3711 case 0:
3712 return ERROR_NONE;
3713 case VE_CANNOT_START_RECORDING:
3714 case VE_MIC_VOL_ERROR:
3715 case VE_GET_MIC_VOL_ERROR:
3716 case VE_CANNOT_ACCESS_MIC_VOL:
3717 return ERROR_REC_DEVICE_OPEN_FAILED;
3718 case VE_SATURATION_WARNING:
3719 return ERROR_REC_DEVICE_SATURATION;
3720 case VE_REC_DEVICE_REMOVED:
3721 return ERROR_REC_DEVICE_REMOVED;
3722 case VE_RUNTIME_REC_WARNING:
3723 case VE_RUNTIME_REC_ERROR:
3724 return ERROR_REC_RUNTIME_ERROR;
3725 case VE_CANNOT_START_PLAYOUT:
3726 case VE_SPEAKER_VOL_ERROR:
3727 case VE_GET_SPEAKER_VOL_ERROR:
3728 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3729 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3730 case VE_RUNTIME_PLAY_WARNING:
3731 case VE_RUNTIME_PLAY_ERROR:
3732 return ERROR_PLAY_RUNTIME_ERROR;
3733 case VE_TYPING_NOISE_WARNING:
3734 return ERROR_REC_TYPING_NOISE_DETECTED;
3735 default:
3736 return VoiceMediaChannel::ERROR_OTHER;
3737 }
3738}
3739
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003740bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3741 int channel_id, const RtpHeaderExtension* extension) {
3742 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003743 int id = 0;
3744 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003745 if (extension) {
3746 enable = true;
3747 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003748 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003749 }
3750 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003751 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003752 return false;
3753 }
3754 return true;
3755}
3756
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003757bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3758 webrtc::ViENetwork* vie_network = NULL;
3759 int vie_channel = -1;
3760 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3761 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3762 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3763 vie_channel = shared_bwe_vie_channel_;
3764 }
3765 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3766 vie_channel) == -1) {
3767 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3768 if (vie_network != NULL) {
3769 // Don't fail if we're tearing down.
3770 return false;
3771 }
3772 }
3773 return true;
3774}
3775
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003776int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003777 size_t res = 0;
3778 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003779 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003780}
3781
3782int WebRtcSoundclipStream::Rewind() {
3783 mem_.Rewind();
3784 // Return -1 to keep VoiceEngine from looping.
3785 return (loop_) ? 0 : -1;
3786}
3787
3788} // namespace cricket
3789
3790#endif // HAVE_WEBRTC_VOICE