blob: ac36ed5ace8224a5c8c89448e73da381704de42d [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
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000056#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
58#ifdef WIN32
59#include <objbase.h> // NOLINT
60#endif
61
62namespace cricket {
63
Brave Yao5225dd82015-03-26 07:39:19 +080064static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065struct CodecPref {
66 const char* name;
67 int clockrate;
68 int channels;
69 int payload_type;
70 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080071 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
Brave Yao5225dd82015-03-26 07:39:19 +080073// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080075 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
76 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
77 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000078 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080079 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
80 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
81 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
82 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080083 { 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}
Minyue Li7100dcd2015-03-27 05:05:59 +0100164
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165static std::string ToString(const webrtc::CodecInst& codec) {
166 std::stringstream ss;
167 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
168 << " (" << codec.pltype << ")";
169 return ss.str();
170}
171
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000172static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000173 const char* delim = "\r\n";
174 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
175 LOG_V(sev) << tok;
176 }
177}
178
179// Severity is an integer because it comes is assumed to be from command line.
180static int SeverityToFilter(int severity) {
181 int filter = webrtc::kTraceNone;
182 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200185 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200188 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000189 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200191 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000192 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
194 }
195 return filter;
196}
197
Minyue Li7100dcd2015-03-27 05:05:59 +0100198static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
199 return (_stricmp(codec.name.c_str(), ref_name) == 0);
200}
201
202static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
203 return (_stricmp(codec.plname, ref_name) == 0);
204}
205
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000206static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
207 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100208 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209 kCodecPrefs[i].clockrate == codec.plfreq) {
210 return kCodecPrefs[i].is_multi_rate;
211 }
212 }
213 return false;
214}
215
216static 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) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100251 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800252 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100253 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800254 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
Minyue Li7100dcd2015-03-27 05:05:59 +0100265// Return true if codec.params[feature] == "1", false otherwise.
266static bool IsCodecFeatureEnabled(const AudioCodec& codec,
267 const char* feature) {
268 int value;
269 return codec.GetParam(feature, &value) && value == 1;
270}
271
272// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
273// otherwise. If the value (either from params or codec.bitrate) <=0, use the
274// default configuration. If the value is beyond feasible bit rate of Opus,
275// clamp it. Returns the Opus bit rate for operation.
276static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
277 int bitrate = 0;
278 bool use_param = true;
279 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
280 bitrate = codec.bitrate;
281 use_param = false;
282 }
283 if (bitrate <= 0) {
284 if (max_playback_rate <= 8000) {
285 bitrate = kOpusBitrateNb;
286 } else if (max_playback_rate <= 16000) {
287 bitrate = kOpusBitrateWb;
288 } else {
289 bitrate = kOpusBitrateFb;
290 }
291
292 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
293 bitrate *= 2;
294 }
295 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
296 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
297 std::string rate_source =
298 use_param ? "Codec parameter \"maxaveragebitrate\"" :
299 "Supplied Opus bitrate";
300 LOG(LS_WARNING) << rate_source
301 << " is invalid and is replaced by: "
302 << bitrate;
303 }
304 return bitrate;
305}
306
307// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
308// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
309static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
310 int value;
311 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
312 return value;
313 }
314 return kOpusDefaultMaxPlaybackRate;
315}
316
317static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
318 bool* enable_codec_fec, int* max_playback_rate,
319 bool* enable_codec_dtx) {
320 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
321 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
322 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
323
324 // If OPUS, change what we send according to the "stereo" codec
325 // parameter, and not the "channels" parameter. We set
326 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
327 // the bitrate is not specified, i.e. is <= zero, we set it to the
328 // appropriate default value for mono or stereo Opus.
329
330 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
331 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
332}
333
334// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
335// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
336// codec.
337static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
338 if (IsCodec(*voe_codec, kG722CodecName)) {
339 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
340 // has changed, and this special case is no longer needed.
341 ASSERT(voe_codec->plfreq != new_plfreq);
342 voe_codec->plfreq = new_plfreq;
343 }
344}
345
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000346// Gets the default set of options applied to the engine. Historically, these
347// were supplied as a combination of flags from the channel manager (ec, agc,
348// ns, and highpass) and the rest hardcoded in InitInternal.
349static AudioOptions GetDefaultEngineOptions() {
350 AudioOptions options;
351 options.echo_cancellation.Set(true);
352 options.auto_gain_control.Set(true);
353 options.noise_suppression.Set(true);
354 options.highpass_filter.Set(true);
355 options.stereo_swapping.Set(false);
356 options.typing_detection.Set(true);
357 options.conference_mode.Set(false);
358 options.adjust_agc_delta.Set(0);
359 options.experimental_agc.Set(false);
360 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100361 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000362 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000363 options.aec_dump.Set(false);
364 return options;
365}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366
Minyue Li7100dcd2015-03-27 05:05:59 +0100367static std::string GetEnableString(bool enable) {
368 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800369}
370
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371class WebRtcSoundclipMedia : public SoundclipMedia {
372 public:
373 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
374 : engine_(engine), webrtc_channel_(-1) {
375 engine_->RegisterSoundclip(this);
376 }
377
378 virtual ~WebRtcSoundclipMedia() {
379 engine_->UnregisterSoundclip(this);
380 if (webrtc_channel_ != -1) {
381 // We shouldn't have to call Disable() here. DeleteChannel() should call
382 // StopPlayout() while deleting the channel. We should fix the bug
383 // inside WebRTC and remove the Disable() call bellow. This work is
384 // tracked by bug http://b/issue?id=5382855.
385 PlaySound(NULL, 0, 0);
386 Disable();
387 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
388 == -1) {
389 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
390 }
391 }
392 }
393
394 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000395 if (!engine_->voe_sc()) {
396 return false;
397 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000398 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399 if (webrtc_channel_ == -1) {
400 LOG_RTCERR0(CreateChannel);
401 return false;
402 }
403 return true;
404 }
405
406 bool Enable() {
407 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
408 LOG_RTCERR1(StartPlayout, webrtc_channel_);
409 return false;
410 }
411 return true;
412 }
413
414 bool Disable() {
415 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
416 LOG_RTCERR1(StopPlayout, webrtc_channel_);
417 return false;
418 }
419 return true;
420 }
421
422 virtual bool PlaySound(const char *buf, int len, int flags) {
423 // The voe file api is not available in chrome.
424 if (!engine_->voe_sc()->file()) {
425 return false;
426 }
427 // Must stop playing the current sound (if any), because we are about to
428 // modify the stream.
429 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
430 == -1) {
431 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
432 return false;
433 }
434
435 if (buf) {
436 stream_.reset(new WebRtcSoundclipStream(buf, len));
437 stream_->set_loop((flags & SF_LOOP) != 0);
438 stream_->Rewind();
439
440 // Play it.
441 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
442 webrtc_channel_, stream_.get()) == -1) {
443 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
444 LOG(LS_ERROR) << "Unable to start soundclip";
445 return false;
446 }
447 } else {
448 stream_.reset();
449 }
450 return true;
451 }
452
453 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
454
455 private:
456 WebRtcVoiceEngine *engine_;
457 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000459};
460
461WebRtcVoiceEngine::WebRtcVoiceEngine()
462 : voe_wrapper_(new VoEWrapper()),
463 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000464 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465 tracing_(new VoETraceWrapper()),
466 adm_(NULL),
467 adm_sc_(NULL),
468 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
469 is_dumping_aec_(false),
470 desired_local_monitor_enable_(false),
471 tx_processor_ssrc_(0),
472 rx_processor_ssrc_(0) {
473 Construct();
474}
475
476WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
477 VoEWrapper* voe_wrapper_sc,
478 VoETraceWrapper* tracing)
479 : voe_wrapper_(voe_wrapper),
480 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000481 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000482 tracing_(tracing),
483 adm_(NULL),
484 adm_sc_(NULL),
485 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
486 is_dumping_aec_(false),
487 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488 tx_processor_ssrc_(0),
489 rx_processor_ssrc_(0) {
490 Construct();
491}
492
493void WebRtcVoiceEngine::Construct() {
494 SetTraceFilter(log_filter_);
495 initialized_ = false;
496 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
497 SetTraceOptions("");
498 if (tracing_->SetTraceCallback(this) == -1) {
499 LOG_RTCERR0(SetTraceCallback);
500 }
501 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
502 LOG_RTCERR0(RegisterVoiceEngineObserver);
503 }
504 // Clear the default agc state.
505 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
506
507 // Load our audio codec list.
508 ConstructCodecs();
509
510 // Load our RTP Header extensions.
511 rtp_header_extensions_.push_back(
512 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
513 kRtpAudioLevelHeaderExtensionDefaultId));
514 rtp_header_extensions_.push_back(
515 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
516 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
517 options_ = GetDefaultEngineOptions();
518}
519
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000520void WebRtcVoiceEngine::ConstructCodecs() {
521 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
522 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
523 for (int i = 0; i < ncodecs; ++i) {
524 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000525 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000526 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100527 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528 continue;
529 }
530
531 const CodecPref* pref = NULL;
532 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100533 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000534 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
535 kCodecPrefs[j].channels == voe_codec.channels) {
536 pref = &kCodecPrefs[j];
537 break;
538 }
539 }
540
541 if (pref) {
542 // Use the payload type that we've configured in our pref table;
543 // use the offset in our pref table to determine the sort order.
544 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
545 voe_codec.rate, voe_codec.channels,
546 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
547 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100548 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000549 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000550 codec.bitrate = 0;
551 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100552 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000553 // Only add fmtp parameters that differ from the spec.
554 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
555 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000556 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000557 }
558 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
559 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000560 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000561 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000562 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000563
564 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000565 // when they can be set to values other than the default.
566 }
567 codecs_.push_back(codec);
568 } else {
569 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
570 }
571 }
572 }
573 // Make sure they are in local preference order.
574 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
575}
576
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000577bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
578 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
579 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000580 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000581 // Change the sample rate of G722 to 8000 to match SDP.
582 MaybeFixupG722(codec, 8000);
583 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000584}
585
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000586WebRtcVoiceEngine::~WebRtcVoiceEngine() {
587 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
588 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
589 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
590 }
591 if (adm_) {
592 voe_wrapper_.reset();
593 adm_->Release();
594 adm_ = NULL;
595 }
596 if (adm_sc_) {
597 voe_wrapper_sc_.reset();
598 adm_sc_->Release();
599 adm_sc_ = NULL;
600 }
601
602 // Test to see if the media processor was deregistered properly
603 ASSERT(SignalRxMediaFrame.is_empty());
604 ASSERT(SignalTxMediaFrame.is_empty());
605
606 tracing_->SetTraceCallback(NULL);
607}
608
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000609bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000610 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000611 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
612 bool res = InitInternal();
613 if (res) {
614 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
615 } else {
616 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
617 Terminate();
618 }
619 return res;
620}
621
622bool WebRtcVoiceEngine::InitInternal() {
623 // Temporarily turn logging level up for the Init call
624 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000625 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000626 SetTraceFilter(extended_filter);
627 SetTraceOptions("");
628
629 // Init WebRtc VoiceEngine.
630 if (voe_wrapper_->base()->Init(adm_) == -1) {
631 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
632 SetTraceFilter(old_filter);
633 return false;
634 }
635
636 SetTraceFilter(old_filter);
637 SetTraceOptions(log_options_);
638
639 // Log the VoiceEngine version info
640 char buffer[1024] = "";
641 voe_wrapper_->base()->GetVersion(buffer);
642 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000643 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644
645 // Save the default AGC configuration settings. This must happen before
646 // calling SetOptions or the default will be overwritten.
647 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
648 LOG_RTCERR0(GetAgcConfig);
649 return false;
650 }
651
652 // Set defaults for options, so that ApplyOptions applies them explicitly
653 // when we clear option (channel) overrides. External clients can still
654 // modify the defaults via SetOptions (on the media engine).
655 if (!SetOptions(GetDefaultEngineOptions())) {
656 return false;
657 }
658
659 // Print our codec list again for the call diagnostic log
660 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
661 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
662 it != codecs_.end(); ++it) {
663 LOG(LS_INFO) << ToString(*it);
664 }
665
666 // Disable the DTMF playout when a tone is sent.
667 // PlayDtmfTone will be used if local playout is needed.
668 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
669 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
670 }
671
672 initialized_ = true;
673 return true;
674}
675
676bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
677 if (voe_wrapper_sc_initialized_) {
678 return true;
679 }
680 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
681 // be false, so subsequent calls to EnsureSoundclipEngineInit will
682 // probably just fail again. That's acceptable behavior.
683#if defined(LINUX) && !defined(HAVE_LIBPULSE)
684 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
685#endif
686
687 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
688 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
689 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
690 return false;
691 }
692
693 // On Windows, tell it to use the default sound (not communication) devices.
694 // First check whether there is a valid sound device for playback.
695 // TODO(juberti): Clean this up when we support setting the soundclip device.
696#ifdef WIN32
697 // The SetPlayoutDevice may not be implemented in the case of external ADM.
698 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
699 // PeerConnection interface never set the adm_sc_, so need to check both
700 // in order to determine if the external adm is used.
701 if (!adm_ && !adm_sc_) {
702 int num_of_devices = 0;
703 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
704 num_of_devices > 0) {
705 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
706 == -1) {
707 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
708 voe_wrapper_sc_->error());
709 return false;
710 }
711 } else {
712 LOG(LS_WARNING) << "No valid sound playout device found.";
713 }
714 }
715#endif
716 voe_wrapper_sc_initialized_ = true;
717 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
718 return true;
719}
720
721void WebRtcVoiceEngine::Terminate() {
722 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
723 initialized_ = false;
724
725 StopAecDump();
726
727 if (voe_wrapper_sc_) {
728 voe_wrapper_sc_initialized_ = false;
729 voe_wrapper_sc_->base()->Terminate();
730 }
731 voe_wrapper_->base()->Terminate();
732 desired_local_monitor_enable_ = false;
733}
734
735int WebRtcVoiceEngine::GetCapabilities() {
736 return AUDIO_SEND | AUDIO_RECV;
737}
738
739VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
740 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
741 if (!ch->valid()) {
742 delete ch;
743 ch = NULL;
744 }
745 return ch;
746}
747
748SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
749 if (!EnsureSoundclipEngineInit()) {
750 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
751 << "initialize.";
752 return NULL;
753 }
754 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
755 if (!soundclip->Init() || !soundclip->Enable()) {
756 delete soundclip;
757 return NULL;
758 }
759 return soundclip;
760}
761
762bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
763 if (!ApplyOptions(options)) {
764 return false;
765 }
766 options_ = options;
767 return true;
768}
769
770bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
771 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
772 if (!ApplyOptions(overrides)) {
773 return false;
774 }
775 option_overrides_ = overrides;
776 return true;
777}
778
779bool WebRtcVoiceEngine::ClearOptionOverrides() {
780 LOG(LS_INFO) << "Clearing option overrides.";
781 AudioOptions options = options_;
782 // Only call ApplyOptions if |options_overrides_| contains overrided options.
783 // ApplyOptions affects NS, AGC other options that is shared between
784 // all WebRtcVoiceEngineChannels.
785 if (option_overrides_ == AudioOptions()) {
786 return true;
787 }
788
789 if (!ApplyOptions(options)) {
790 return false;
791 }
792 option_overrides_ = AudioOptions();
793 return true;
794}
795
796// AudioOptions defaults are set in InitInternal (for options with corresponding
797// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
798bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
799 AudioOptions options = options_in; // The options are modified below.
800 // kEcConference is AEC with high suppression.
801 webrtc::EcModes ec_mode = webrtc::kEcConference;
802 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
803 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
804 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
805 bool aecm_comfort_noise = false;
806 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
807 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
808 << aecm_comfort_noise << " (default is false).";
809 }
810
811#if defined(IOS)
812 // On iOS, VPIO provides built-in EC and AGC.
813 options.echo_cancellation.Set(false);
814 options.auto_gain_control.Set(false);
815#elif defined(ANDROID)
816 ec_mode = webrtc::kEcAecm;
817#endif
818
819#if defined(IOS) || defined(ANDROID)
820 // Set the AGC mode for iOS as well despite disabling it above, to avoid
821 // unsupported configuration errors from webrtc.
822 agc_mode = webrtc::kAgcFixedDigital;
823 options.typing_detection.Set(false);
824 options.experimental_agc.Set(false);
825 options.experimental_aec.Set(false);
826 options.experimental_ns.Set(false);
827#endif
828
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100829 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
830 // where the feature is not supported.
831 bool use_delay_agnostic_aec = false;
832#if !defined(IOS)
833 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
834 if (use_delay_agnostic_aec) {
835 options.echo_cancellation.Set(true);
836 options.experimental_aec.Set(true);
837 ec_mode = webrtc::kEcConference;
838 }
839 }
840#endif
841
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000842 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
843
844 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
845
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000846 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000847 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000848 // Check if platform supports built-in EC. Currently only supported on
849 // Android and in combination with Java based audio layer.
850 // TODO(henrika): investigate possibility to support built-in EC also
851 // in combination with Open SL ES audio.
852 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200853 if (built_in_aec && !use_delay_agnostic_aec) {
854 // Built-in EC exists on this device and use_delay_agnostic_aec is not
855 // overriding it. Enable/Disable it according to the echo_cancellation
856 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200857 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
858 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100859 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000860 // i.e., replace the software EC with the built-in EC.
861 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000862 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000863 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
864 }
865 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000866 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
867 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
868 return false;
869 } else {
870 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
871 << " with mode " << ec_mode;
872 }
873#if !defined(ANDROID)
874 // TODO(ajm): Remove the error return on Android from webrtc.
875 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
876 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
877 return false;
878 }
879#endif
880 if (ec_mode == webrtc::kEcAecm) {
881 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
882 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
883 return false;
884 }
885 }
886 }
887
888 bool auto_gain_control;
889 if (options.auto_gain_control.Get(&auto_gain_control)) {
890 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
891 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
892 return false;
893 } else {
894 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
895 << " with mode " << agc_mode;
896 }
897 }
898
899 if (options.tx_agc_target_dbov.IsSet() ||
900 options.tx_agc_digital_compression_gain.IsSet() ||
901 options.tx_agc_limiter.IsSet()) {
902 // Override default_agc_config_. Generally, an unset option means "leave
903 // the VoE bits alone" in this function, so we want whatever is set to be
904 // stored as the new "default". If we didn't, then setting e.g.
905 // tx_agc_target_dbov would reset digital compression gain and limiter
906 // settings.
907 // Also, if we don't update default_agc_config_, then adjust_agc_delta
908 // would be an offset from the original values, and not whatever was set
909 // explicitly.
910 default_agc_config_.targetLeveldBOv =
911 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
912 default_agc_config_.targetLeveldBOv);
913 default_agc_config_.digitalCompressionGaindB =
914 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
915 default_agc_config_.digitalCompressionGaindB);
916 default_agc_config_.limiterEnable =
917 options.tx_agc_limiter.GetWithDefaultIfUnset(
918 default_agc_config_.limiterEnable);
919 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
920 LOG_RTCERR3(SetAgcConfig,
921 default_agc_config_.targetLeveldBOv,
922 default_agc_config_.digitalCompressionGaindB,
923 default_agc_config_.limiterEnable);
924 return false;
925 }
926 }
927
928 bool noise_suppression;
929 if (options.noise_suppression.Get(&noise_suppression)) {
930 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
931 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
932 return false;
933 } else {
934 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
935 << " with mode " << ns_mode;
936 }
937 }
938
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000939 bool highpass_filter;
940 if (options.highpass_filter.Get(&highpass_filter)) {
941 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
942 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
943 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
944 return false;
945 }
946 }
947
948 bool stereo_swapping;
949 if (options.stereo_swapping.Get(&stereo_swapping)) {
950 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
951 voep->EnableStereoChannelSwapping(stereo_swapping);
952 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
953 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
954 return false;
955 }
956 }
957
958 bool typing_detection;
959 if (options.typing_detection.Get(&typing_detection)) {
960 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
961 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
962 // In case of error, log the info and continue
963 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
964 }
965 }
966
967 int adjust_agc_delta;
968 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
969 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
970 if (!AdjustAgcLevel(adjust_agc_delta)) {
971 return false;
972 }
973 }
974
975 bool aec_dump;
976 if (options.aec_dump.Get(&aec_dump)) {
977 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
978 if (aec_dump)
979 StartAecDump(kAecDumpByAudioOptionFilename);
980 else
981 StopAecDump();
982 }
983
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000984 webrtc::Config config;
985
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100986 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
987 bool delay_agnostic_aec;
988 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
989 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
990 config.Set<webrtc::ReportedDelay>(
991 new webrtc::ReportedDelay(!delay_agnostic_aec));
992 }
993
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000994 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000995 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000996 if (experimental_aec_.Get(&experimental_aec)) {
997 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
998 config.Set<webrtc::DelayCorrection>(
999 new webrtc::DelayCorrection(experimental_aec));
1000 }
1001
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001002 experimental_ns_.SetFrom(options.experimental_ns);
1003 bool experimental_ns;
1004 if (experimental_ns_.Get(&experimental_ns)) {
1005 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
1006 config.Set<webrtc::ExperimentalNs>(
1007 new webrtc::ExperimentalNs(experimental_ns));
1008 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001009
1010 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
1011 // returns NULL on audio_processing().
1012 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
1013 if (audioproc) {
1014 audioproc->SetExtraOptions(config);
1015 }
1016
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001017 uint32 recording_sample_rate;
1018 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1019 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1020 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1021 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1022 }
1023 }
1024
1025 uint32 playout_sample_rate;
1026 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1027 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1028 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1029 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1030 }
1031 }
1032
1033 return true;
1034}
1035
1036bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1037 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1038 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1039 LOG_RTCERR1(SetDelayOffsetMs, offset);
1040 return false;
1041 }
1042
1043 return true;
1044}
1045
1046struct ResumeEntry {
1047 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1048 : channel(c),
1049 playout(p),
1050 send(s) {
1051 }
1052
1053 WebRtcVoiceMediaChannel *channel;
1054 bool playout;
1055 SendFlags send;
1056};
1057
1058// TODO(juberti): Refactor this so that the core logic can be used to set the
1059// soundclip device. At that time, reinstate the soundclip pause/resume code.
1060bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1061 const Device* out_device) {
1062#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001063 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001064 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001065 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001066 kDefaultAudioDeviceId;
1067 // The device manager uses -1 as the default device, which was the case for
1068 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1069#ifndef WIN32
1070 if (-1 == in_id) {
1071 in_id = kDefaultAudioDeviceId;
1072 }
1073 if (-1 == out_id) {
1074 out_id = kDefaultAudioDeviceId;
1075 }
1076#endif
1077
1078 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1079 in_device->name : "Default device";
1080 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1081 out_device->name : "Default device";
1082 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1083 << ") and speaker to (id=" << out_id << ", name=" << out_name
1084 << ")";
1085
1086 // If we're running the local monitor, we need to stop it first.
1087 bool ret = true;
1088 if (!PauseLocalMonitor()) {
1089 LOG(LS_WARNING) << "Failed to pause local monitor";
1090 ret = false;
1091 }
1092
1093 // Must also pause all audio playback and capture.
1094 for (ChannelList::const_iterator i = channels_.begin();
1095 i != channels_.end(); ++i) {
1096 WebRtcVoiceMediaChannel *channel = *i;
1097 if (!channel->PausePlayout()) {
1098 LOG(LS_WARNING) << "Failed to pause playout";
1099 ret = false;
1100 }
1101 if (!channel->PauseSend()) {
1102 LOG(LS_WARNING) << "Failed to pause send";
1103 ret = false;
1104 }
1105 }
1106
1107 // Find the recording device id in VoiceEngine and set recording device.
1108 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1109 ret = false;
1110 }
1111 if (ret) {
1112 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1113 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1114 ret = false;
1115 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001116 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1117 if (ap)
1118 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 }
1120
1121 // Find the playout device id in VoiceEngine and set playout device.
1122 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1123 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1124 ret = false;
1125 }
1126 if (ret) {
1127 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001128 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129 ret = false;
1130 }
1131 }
1132
1133 // Resume all audio playback and capture.
1134 for (ChannelList::const_iterator i = channels_.begin();
1135 i != channels_.end(); ++i) {
1136 WebRtcVoiceMediaChannel *channel = *i;
1137 if (!channel->ResumePlayout()) {
1138 LOG(LS_WARNING) << "Failed to resume playout";
1139 ret = false;
1140 }
1141 if (!channel->ResumeSend()) {
1142 LOG(LS_WARNING) << "Failed to resume send";
1143 ret = false;
1144 }
1145 }
1146
1147 // Resume local monitor.
1148 if (!ResumeLocalMonitor()) {
1149 LOG(LS_WARNING) << "Failed to resume local monitor";
1150 ret = false;
1151 }
1152
1153 if (ret) {
1154 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1155 << ") and speaker to (id="<< out_id << " name=" << out_name
1156 << ")";
1157 }
1158
1159 return ret;
1160#else
1161 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001162#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163}
1164
1165bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1166 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1167 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001168#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 *rtc_id = dev_id;
1170 return true;
1171#else
1172 // In Windows and Mac, we need to find the VoiceEngine device id by name
1173 // unless the input dev_id is the default device id.
1174 if (kDefaultAudioDeviceId == dev_id) {
1175 *rtc_id = dev_id;
1176 return true;
1177 }
1178
1179 // Get the number of VoiceEngine audio devices.
1180 int count = 0;
1181 if (is_input) {
1182 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1183 LOG_RTCERR0(GetNumOfRecordingDevices);
1184 return false;
1185 }
1186 } else {
1187 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1188 LOG_RTCERR0(GetNumOfPlayoutDevices);
1189 return false;
1190 }
1191 }
1192
1193 for (int i = 0; i < count; ++i) {
1194 char name[128];
1195 char guid[128];
1196 if (is_input) {
1197 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1198 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1199 } else {
1200 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1201 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1202 }
1203
1204 std::string webrtc_name(name);
1205 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1206 *rtc_id = i;
1207 return true;
1208 }
1209 }
1210 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1211 return false;
1212#endif
1213}
1214
1215bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1216 unsigned int ulevel;
1217 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1218 LOG_RTCERR1(GetSpeakerVolume, level);
1219 return false;
1220 }
1221 *level = ulevel;
1222 return true;
1223}
1224
1225bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1226 ASSERT(level >= 0 && level <= 255);
1227 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1228 LOG_RTCERR1(SetSpeakerVolume, level);
1229 return false;
1230 }
1231 return true;
1232}
1233
1234int WebRtcVoiceEngine::GetInputLevel() {
1235 unsigned int ulevel;
1236 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1237 static_cast<int>(ulevel) : -1;
1238}
1239
1240bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1241 desired_local_monitor_enable_ = enable;
1242 return ChangeLocalMonitor(desired_local_monitor_enable_);
1243}
1244
1245bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1246 // The voe file api is not available in chrome.
1247 if (!voe_wrapper_->file()) {
1248 return false;
1249 }
1250 if (enable && !monitor_) {
1251 monitor_.reset(new WebRtcMonitorStream);
1252 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1253 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1254 // Must call Stop() because there are some cases where Start will report
1255 // failure but still change the state, and if we leave VE in the on state
1256 // then it could crash later when trying to invoke methods on our monitor.
1257 voe_wrapper_->file()->StopRecordingMicrophone();
1258 monitor_.reset();
1259 return false;
1260 }
1261 } else if (!enable && monitor_) {
1262 voe_wrapper_->file()->StopRecordingMicrophone();
1263 monitor_.reset();
1264 }
1265 return true;
1266}
1267
1268bool WebRtcVoiceEngine::PauseLocalMonitor() {
1269 return ChangeLocalMonitor(false);
1270}
1271
1272bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1273 return ChangeLocalMonitor(desired_local_monitor_enable_);
1274}
1275
1276const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1277 return codecs_;
1278}
1279
1280bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1281 return FindWebRtcCodec(in, NULL);
1282}
1283
1284// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1285bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1286 webrtc::CodecInst* out) {
1287 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1288 for (int i = 0; i < ncodecs; ++i) {
1289 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001290 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1292 voe_codec.rate, voe_codec.channels, 0);
1293 bool multi_rate = IsCodecMultiRate(voe_codec);
1294 // Allow arbitrary rates for ISAC to be specified.
1295 if (multi_rate) {
1296 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1297 codec.bitrate = 0;
1298 }
1299 if (codec.Matches(in)) {
1300 if (out) {
1301 // Fixup the payload type.
1302 voe_codec.pltype = in.id;
1303
1304 // Set bitrate if specified.
1305 if (multi_rate && in.bitrate != 0) {
1306 voe_codec.rate = in.bitrate;
1307 }
1308
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001309 // Reset G722 sample rate to 16000 to match WebRTC.
1310 MaybeFixupG722(&voe_codec, 16000);
1311
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001313 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001315 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1317 }
1318 *out = voe_codec;
1319 }
1320 return true;
1321 }
1322 }
1323 }
1324 return false;
1325}
1326const std::vector<RtpHeaderExtension>&
1327WebRtcVoiceEngine::rtp_header_extensions() const {
1328 return rtp_header_extensions_;
1329}
1330
1331void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1332 // if min_sev == -1, we keep the current log level.
1333 if (min_sev >= 0) {
1334 SetTraceFilter(SeverityToFilter(min_sev));
1335 }
1336 log_options_ = filter;
1337 SetTraceOptions(initialized_ ? log_options_ : "");
1338}
1339
1340int WebRtcVoiceEngine::GetLastEngineError() {
1341 return voe_wrapper_->error();
1342}
1343
1344void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1345 log_filter_ = filter;
1346 tracing_->SetTraceFilter(filter);
1347}
1348
1349// We suppport three different logging settings for VoiceEngine:
1350// 1. Observer callback that goes into talk diagnostic logfile.
1351// Use --logfile and --loglevel
1352//
1353// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1354// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1355//
1356// 3. EC log and dump for debugging QualityEngine.
1357// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1358//
1359// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1360// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1361void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1362 // Set encrypted trace file.
1363 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001364 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 std::vector<std::string>::iterator tracefile =
1366 std::find(opts.begin(), opts.end(), "tracefile");
1367 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1368 // Write encrypted debug output (at same loglevel) to file
1369 // EncryptedTraceFile no longer supported.
1370 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1371 LOG_RTCERR1(SetTraceFile, *tracefile);
1372 }
1373 }
1374
wu@webrtc.org97077a32013-10-25 21:18:33 +00001375 // Allow trace options to override the trace filter. We default
1376 // it to log_filter_ (as a translation of libjingle log levels)
1377 // elsewhere, but this allows clients to explicitly set webrtc
1378 // log levels.
1379 std::vector<std::string>::iterator tracefilter =
1380 std::find(opts.begin(), opts.end(), "tracefilter");
1381 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001382 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001383 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1384 }
1385 }
1386
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 // Set AEC dump file
1388 std::vector<std::string>::iterator recordEC =
1389 std::find(opts.begin(), opts.end(), "recordEC");
1390 if (recordEC != opts.end()) {
1391 ++recordEC;
1392 if (recordEC != opts.end())
1393 StartAecDump(recordEC->c_str());
1394 else
1395 StopAecDump();
1396 }
1397}
1398
1399// Ignore spammy trace messages, mostly from the stats API when we haven't
1400// gotten RTCP info yet from the remote side.
1401bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1402 static const char* kTracesToIgnore[] = {
1403 "\tfailed to GetReportBlockInformation",
1404 "GetRecCodec() failed to get received codec",
1405 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1406 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1407 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1408 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1409 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1410 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1411 "SenderInfoReceived No received SR",
1412 "StatisticsRTP() no statistics available",
1413 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1414 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1415 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1416 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1417 NULL
1418 };
1419 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1420 if (trace.find(*p) != std::string::npos) {
1421 return true;
1422 }
1423 }
1424 return false;
1425}
1426
1427void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1428 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001429 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001431 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001433 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001435 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001437 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438
1439 // Skip past boilerplate prefix text
1440 if (length < 72) {
1441 std::string msg(trace, length);
1442 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1443 LOG_V(sev) << msg;
1444 } else {
1445 std::string msg(trace + 71, length - 72);
1446 if (!ShouldIgnoreTrace(msg)) {
1447 LOG_V(sev) << "webrtc: " << msg;
1448 }
1449 }
1450}
1451
1452void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001453 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 WebRtcVoiceMediaChannel* channel = NULL;
1455 uint32 ssrc = 0;
1456 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1457 << channel_num << ".";
1458 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1459 ASSERT(channel != NULL);
1460 channel->OnError(ssrc, err_code);
1461 } else {
1462 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1463 << " could not be found in channel list when error reported.";
1464 }
1465}
1466
1467bool WebRtcVoiceEngine::FindChannelAndSsrc(
1468 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1469 ASSERT(channel != NULL && ssrc != NULL);
1470
1471 *channel = NULL;
1472 *ssrc = 0;
1473 // Find corresponding channel and ssrc
1474 for (ChannelList::const_iterator it = channels_.begin();
1475 it != channels_.end(); ++it) {
1476 ASSERT(*it != NULL);
1477 if ((*it)->FindSsrc(channel_num, ssrc)) {
1478 *channel = *it;
1479 return true;
1480 }
1481 }
1482
1483 return false;
1484}
1485
1486// This method will search through the WebRtcVoiceMediaChannels and
1487// obtain the voice engine's channel number.
1488bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1489 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1490 ASSERT(channel_num != NULL);
1491 ASSERT(direction == MPD_RX || direction == MPD_TX);
1492
1493 *channel_num = -1;
1494 // Find corresponding channel for ssrc.
1495 for (ChannelList::const_iterator it = channels_.begin();
1496 it != channels_.end(); ++it) {
1497 ASSERT(*it != NULL);
1498 if (direction & MPD_RX) {
1499 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1500 }
1501 if (*channel_num == -1 && (direction & MPD_TX)) {
1502 *channel_num = (*it)->GetSendChannelNum(ssrc);
1503 }
1504 if (*channel_num != -1) {
1505 return true;
1506 }
1507 }
1508 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1509 return false;
1510}
1511
1512void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001513 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514 channels_.push_back(channel);
1515}
1516
1517void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001518 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519 ChannelList::iterator i = std::find(channels_.begin(),
1520 channels_.end(),
1521 channel);
1522 if (i != channels_.end()) {
1523 channels_.erase(i);
1524 }
1525}
1526
1527void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1528 soundclips_.push_back(soundclip);
1529}
1530
1531void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1532 SoundclipList::iterator i = std::find(soundclips_.begin(),
1533 soundclips_.end(),
1534 soundclip);
1535 if (i != soundclips_.end()) {
1536 soundclips_.erase(i);
1537 }
1538}
1539
1540// Adjusts the default AGC target level by the specified delta.
1541// NB: If we start messing with other config fields, we'll want
1542// to save the current webrtc::AgcConfig as well.
1543bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1544 webrtc::AgcConfig config = default_agc_config_;
1545 config.targetLeveldBOv -= delta;
1546
1547 LOG(LS_INFO) << "Adjusting AGC level from default -"
1548 << default_agc_config_.targetLeveldBOv << "dB to -"
1549 << config.targetLeveldBOv << "dB";
1550
1551 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1552 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1553 return false;
1554 }
1555 return true;
1556}
1557
1558bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1559 webrtc::AudioDeviceModule* adm_sc) {
1560 if (initialized_) {
1561 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1562 return false;
1563 }
1564 if (adm_) {
1565 adm_->Release();
1566 adm_ = NULL;
1567 }
1568 if (adm) {
1569 adm_ = adm;
1570 adm_->AddRef();
1571 }
1572
1573 if (adm_sc_) {
1574 adm_sc_->Release();
1575 adm_sc_ = NULL;
1576 }
1577 if (adm_sc) {
1578 adm_sc_ = adm_sc;
1579 adm_sc_->AddRef();
1580 }
1581 return true;
1582}
1583
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001584bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1585 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001586 if (!aec_dump_file_stream) {
1587 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001588 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001589 LOG(LS_WARNING) << "Could not close file.";
1590 return false;
1591 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001592 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001593 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001594 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001595 LOG_RTCERR0(StartDebugRecording);
1596 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001597 return false;
1598 }
1599 is_dumping_aec_ = true;
1600 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001601}
1602
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603bool WebRtcVoiceEngine::RegisterProcessor(
1604 uint32 ssrc,
1605 VoiceProcessor* voice_processor,
1606 MediaProcessorDirection direction) {
1607 bool register_with_webrtc = false;
1608 int channel_id = -1;
1609 bool success = false;
1610 uint32* processor_ssrc = NULL;
1611 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1612 if (voice_processor == NULL || !found_channel) {
1613 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1614 << " foundChannel: " << found_channel;
1615 return false;
1616 }
1617
1618 webrtc::ProcessingTypes processing_type;
1619 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001620 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 if (direction == MPD_RX) {
1622 processing_type = webrtc::kPlaybackAllChannelsMixed;
1623 if (SignalRxMediaFrame.is_empty()) {
1624 register_with_webrtc = true;
1625 processor_ssrc = &rx_processor_ssrc_;
1626 }
1627 SignalRxMediaFrame.connect(voice_processor,
1628 &VoiceProcessor::OnFrame);
1629 } else {
1630 processing_type = webrtc::kRecordingPerChannel;
1631 if (SignalTxMediaFrame.is_empty()) {
1632 register_with_webrtc = true;
1633 processor_ssrc = &tx_processor_ssrc_;
1634 }
1635 SignalTxMediaFrame.connect(voice_processor,
1636 &VoiceProcessor::OnFrame);
1637 }
1638 }
1639 if (register_with_webrtc) {
1640 // TODO(janahan): when registering consider instantiating a
1641 // a VoeMediaProcess object and not make the engine extend the interface.
1642 if (voe()->media() && voe()->media()->
1643 RegisterExternalMediaProcessing(channel_id,
1644 processing_type,
1645 *this) != -1) {
1646 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1647 << channel_id;
1648 *processor_ssrc = ssrc;
1649 success = true;
1650 } else {
1651 LOG_RTCERR2(RegisterExternalMediaProcessing,
1652 channel_id,
1653 processing_type);
1654 success = false;
1655 }
1656 } else {
1657 // If we don't have to register with the engine, we just needed to
1658 // connect a new processor, set success to true;
1659 success = true;
1660 }
1661 return success;
1662}
1663
1664bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1665 MediaProcessorDirection channel_direction,
1666 uint32 ssrc,
1667 VoiceProcessor* voice_processor,
1668 MediaProcessorDirection processor_direction) {
1669 bool success = true;
1670 FrameSignal* signal;
1671 webrtc::ProcessingTypes processing_type;
1672 uint32* processor_ssrc = NULL;
1673 if (channel_direction == MPD_RX) {
1674 signal = &SignalRxMediaFrame;
1675 processing_type = webrtc::kPlaybackAllChannelsMixed;
1676 processor_ssrc = &rx_processor_ssrc_;
1677 } else {
1678 signal = &SignalTxMediaFrame;
1679 processing_type = webrtc::kRecordingPerChannel;
1680 processor_ssrc = &tx_processor_ssrc_;
1681 }
1682
1683 int deregister_id = -1;
1684 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001685 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1687 signal->disconnect(voice_processor);
1688 int channel_id = -1;
1689 bool found_channel = FindChannelNumFromSsrc(ssrc,
1690 channel_direction,
1691 &channel_id);
1692 if (signal->is_empty() && found_channel) {
1693 deregister_id = channel_id;
1694 }
1695 }
1696 }
1697 if (deregister_id != -1) {
1698 if (voe()->media() &&
1699 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1700 processing_type) != -1) {
1701 *processor_ssrc = 0;
1702 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1703 << deregister_id;
1704 } else {
1705 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1706 deregister_id,
1707 processing_type);
1708 success = false;
1709 }
1710 }
1711 return success;
1712}
1713
1714bool WebRtcVoiceEngine::UnregisterProcessor(
1715 uint32 ssrc,
1716 VoiceProcessor* voice_processor,
1717 MediaProcessorDirection direction) {
1718 bool success = true;
1719 if (voice_processor == NULL) {
1720 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1721 << ssrc;
1722 return false;
1723 }
1724 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1725 success = false;
1726 }
1727 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1728 success = false;
1729 }
1730 return success;
1731}
1732
1733// Implementing method from WebRtc VoEMediaProcess interface
1734// Do not lock mux_channel_cs_ in this callback.
1735void WebRtcVoiceEngine::Process(int channel,
1736 webrtc::ProcessingTypes type,
1737 int16_t audio10ms[],
1738 int length,
1739 int sampling_freq,
1740 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001741 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1743 if (type == webrtc::kPlaybackAllChannelsMixed) {
1744 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1745 } else if (type == webrtc::kRecordingPerChannel) {
1746 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1747 } else {
1748 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1749 << " channel: " << channel << " type: " << type
1750 << " tx_ssrc: " << tx_processor_ssrc_
1751 << " rx_ssrc: " << rx_processor_ssrc_;
1752 }
1753}
1754
1755void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1756 if (!is_dumping_aec_) {
1757 // Start dumping AEC when we are not dumping.
1758 if (voe_wrapper_->processing()->StartDebugRecording(
1759 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001760 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 } else {
1762 is_dumping_aec_ = true;
1763 }
1764 }
1765}
1766
1767void WebRtcVoiceEngine::StopAecDump() {
1768 if (is_dumping_aec_) {
1769 // Stop dumping AEC when we are dumping.
1770 if (voe_wrapper_->processing()->StopDebugRecording() !=
1771 webrtc::AudioProcessing::kNoError) {
1772 LOG_RTCERR0(StopDebugRecording);
1773 }
1774 is_dumping_aec_ = false;
1775 }
1776}
1777
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001778int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001779 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001780}
1781
1782int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1783 return CreateVoiceChannel(voe_wrapper_.get());
1784}
1785
1786int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1787 return CreateVoiceChannel(voe_wrapper_sc_.get());
1788}
1789
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001790class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1791 : public AudioRenderer::Sink {
1792 public:
1793 WebRtcVoiceChannelRenderer(int ch,
1794 webrtc::AudioTransport* voe_audio_transport)
1795 : channel_(ch),
1796 voe_audio_transport_(voe_audio_transport),
1797 renderer_(NULL) {
1798 }
1799 virtual ~WebRtcVoiceChannelRenderer() {
1800 Stop();
1801 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001802
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001803 // Starts the rendering by setting a sink to the renderer to get data
1804 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001805 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001806 // TODO(xians): Make sure Start() is called only once.
1807 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001808 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001809 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001810 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001811 ASSERT(renderer_ == renderer);
1812 return;
1813 }
1814
1815 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1816 // in getUserMedia by default.
1817 renderer->AddChannel(channel_);
1818 renderer->SetSink(this);
1819 renderer_ = renderer;
1820 }
1821
1822 // Stops rendering by setting the sink of the renderer to NULL. No data
1823 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001824 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001825 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001826 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001827 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001828 return;
1829
1830 renderer_->RemoveChannel(channel_);
1831 renderer_->SetSink(NULL);
1832 renderer_ = NULL;
1833 }
1834
1835 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001836 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001837 void OnData(const void* audio_data,
1838 int bits_per_sample,
1839 int sample_rate,
1840 int number_of_channels,
1841 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001842 voe_audio_transport_->OnData(channel_,
1843 audio_data,
1844 bits_per_sample,
1845 sample_rate,
1846 number_of_channels,
1847 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001848 }
1849
1850 // Callback from the |renderer_| when it is going away. In case Start() has
1851 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001852 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001853 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001854 // Set |renderer_| to NULL to make sure no more callback will get into
1855 // the renderer.
1856 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001857 }
1858
1859 // Accessor to the VoE channel ID.
1860 int channel() const { return channel_; }
1861
1862 private:
1863 const int channel_;
1864 webrtc::AudioTransport* const voe_audio_transport_;
1865
1866 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1867 // PeerConnection will make sure invalidating the pointer before the object
1868 // goes away.
1869 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001870
1871 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001872 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001873};
1874
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875// WebRtcVoiceMediaChannel
1876WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1877 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1878 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001879 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001880 send_bitrate_setting_(false),
1881 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882 options_(),
1883 dtmf_allowed_(false),
1884 desired_playout_(false),
1885 nack_enabled_(false),
1886 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001887 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 desired_send_(SEND_NOTHING),
1889 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001890 shared_bwe_vie_(NULL),
1891 shared_bwe_vie_channel_(-1),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001892 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 default_receive_ssrc_(0) {
1894 engine->RegisterChannel(this);
1895 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1896 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001897 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898}
1899
1900WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1901 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1902 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001903 SetupSharedBandwidthEstimation(NULL, -1);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001904 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001906 // Remove any remaining send streams, the default channel will be deleted
1907 // later.
1908 while (!send_channels_.empty())
1909 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910
1911 // Unregister ourselves from the engine.
1912 engine()->UnregisterChannel(this);
1913 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001914 while (!receive_channels_.empty()) {
1915 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001917 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001919 // Delete the default channel.
1920 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921}
1922
1923bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1924 LOG(LS_INFO) << "Setting voice channel options: "
1925 << options.ToString();
1926
wu@webrtc.orgde305012013-10-31 15:40:38 +00001927 // Check if DSCP value is changed from previous.
1928 bool dscp_option_changed = (options_.dscp != options.dscp);
1929
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001930 // TODO(xians): Add support to set different options for different send
1931 // streams after we support multiple APMs.
1932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 // We retain all of the existing options, and apply the given ones
1934 // on top. This means there is no way to "clear" options such that
1935 // they go back to the engine default.
1936 options_.SetAll(options);
1937
1938 if (send_ != SEND_NOTHING) {
1939 if (!engine()->SetOptionOverrides(options_)) {
1940 LOG(LS_WARNING) <<
1941 "Failed to engine SetOptionOverrides during channel SetOptions.";
1942 return false;
1943 }
1944 } else {
1945 // Will be interpreted when appropriate.
1946 }
1947
wu@webrtc.org97077a32013-10-25 21:18:33 +00001948 // Receiver-side auto gain control happens per channel, so set it here from
1949 // options. Note that, like conference mode, setting it on the engine won't
1950 // have the desired effect, since voice channels don't inherit options from
1951 // the media engine when those options are applied per-channel.
1952 bool rx_auto_gain_control;
1953 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1954 if (engine()->voe()->processing()->SetRxAgcStatus(
1955 voe_channel(), rx_auto_gain_control,
1956 webrtc::kAgcFixedDigital) == -1) {
1957 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1958 return false;
1959 } else {
1960 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1961 << " with mode " << webrtc::kAgcFixedDigital;
1962 }
1963 }
1964 if (options.rx_agc_target_dbov.IsSet() ||
1965 options.rx_agc_digital_compression_gain.IsSet() ||
1966 options.rx_agc_limiter.IsSet()) {
1967 webrtc::AgcConfig config;
1968 // If only some of the options are being overridden, get the current
1969 // settings for the channel and bail if they aren't available.
1970 if (!options.rx_agc_target_dbov.IsSet() ||
1971 !options.rx_agc_digital_compression_gain.IsSet() ||
1972 !options.rx_agc_limiter.IsSet()) {
1973 if (engine()->voe()->processing()->GetRxAgcConfig(
1974 voe_channel(), config) != 0) {
1975 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1976 << "channel " << voe_channel() << ". Since not all rx "
1977 << "agc options are specified, unable to safely set rx "
1978 << "agc options.";
1979 return false;
1980 }
1981 }
1982 config.targetLeveldBOv =
1983 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1984 config.targetLeveldBOv);
1985 config.digitalCompressionGaindB =
1986 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1987 config.digitalCompressionGaindB);
1988 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1989 config.limiterEnable);
1990 if (engine()->voe()->processing()->SetRxAgcConfig(
1991 voe_channel(), config) == -1) {
1992 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1993 config.digitalCompressionGaindB, config.limiterEnable);
1994 return false;
1995 }
1996 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001997 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001998 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001999 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002000 dscp = kAudioDscpValue;
2001 if (MediaChannel::SetDscp(dscp) != 0) {
2002 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
2003 }
2004 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00002005
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002006 // Force update of Video Engine BWE forwarding to reflect experiment setting.
2007 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
2008 shared_bwe_vie_channel_)) {
2009 return false;
2010 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002011 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 LOG(LS_INFO) << "Set voice channel options. Current options: "
2014 << options_.ToString();
2015 return true;
2016}
2017
2018bool WebRtcVoiceMediaChannel::SetRecvCodecs(
2019 const std::vector<AudioCodec>& codecs) {
2020 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021 LOG(LS_INFO) << "Setting receive voice codecs:";
2022
2023 std::vector<AudioCodec> new_codecs;
2024 // Find all new codecs. We allow adding new codecs but don't allow changing
2025 // the payload type of codecs that is already configured since we might
2026 // already be receiving packets with that payload type.
2027 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002028 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 AudioCodec old_codec;
2030 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2031 if (old_codec.id != it->id) {
2032 LOG(LS_ERROR) << it->name << " payload type changed.";
2033 return false;
2034 }
2035 } else {
2036 new_codecs.push_back(*it);
2037 }
2038 }
2039 if (new_codecs.empty()) {
2040 // There are no new codecs to configure. Already configured codecs are
2041 // never removed.
2042 return true;
2043 }
2044
2045 if (playout_) {
2046 // Receive codecs can not be changed while playing. So we temporarily
2047 // pause playout.
2048 PausePlayout();
2049 }
2050
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002051 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002052 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2053 it != new_codecs.end() && ret; ++it) {
2054 webrtc::CodecInst voe_codec;
2055 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2056 LOG(LS_INFO) << ToString(*it);
2057 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002058 if (default_receive_ssrc_ == 0) {
2059 // Set the receive codecs on the default channel explicitly if the
2060 // default channel is not used by |receive_channels_|, this happens in
2061 // conference mode or in non-conference mode when there is no playout
2062 // channel.
2063 // TODO(xians): Figure out how we use the default channel in conference
2064 // mode.
2065 if (engine()->voe()->codec()->SetRecPayloadType(
2066 voe_channel(), voe_codec) == -1) {
2067 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2068 ret = false;
2069 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002070 }
2071
2072 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002073 for (ChannelMap::iterator it = receive_channels_.begin();
2074 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002075 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002076 it->second->channel(), voe_codec) == -1) {
2077 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002078 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 ret = false;
2080 }
2081 }
2082 } else {
2083 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2084 ret = false;
2085 }
2086 }
2087 if (ret) {
2088 recv_codecs_ = codecs;
2089 }
2090
2091 if (desired_playout_ && !playout_) {
2092 ResumePlayout();
2093 }
2094 return ret;
2095}
2096
2097bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002098 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002099 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002100 engine()->voe()->codec()->SetVADStatus(channel, false);
2101 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002102 engine()->voe()->rtp()->SetREDStatus(channel, false);
2103 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002104
2105 // Scan through the list to figure out the codec to use for sending, along
2106 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002107 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 webrtc::CodecInst send_codec;
2109 memset(&send_codec, 0, sizeof(send_codec));
2110
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002111 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002112 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01002113 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00002114 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002115
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002116 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2118 it != codecs.end(); ++it) {
2119 // Ignore codecs we don't know about. The negotiation step should prevent
2120 // this, but double-check to be sure.
2121 webrtc::CodecInst voe_codec;
2122 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002123 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002124 continue;
2125 }
2126
Minyue Li7100dcd2015-03-27 05:05:59 +01002127 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002128 // Skip telephone-event/CN codec, which will be handled later.
2129 continue;
2130 }
2131
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002132 // We'll use the first codec in the list to actually send audio data.
2133 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002134 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002135 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01002136 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002137 // Parse out the RED parameters. If we fail, just ignore RED;
2138 // we don't support all possible params/usage scenarios.
2139 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2140 continue;
2141 }
2142
2143 // Enable redundant encoding of the specified codec. Treat any
2144 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002145 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2146 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2147 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002148 return false;
2149 }
2150 } else {
2151 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002152 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01002153 // For Opus as the send codec, we are to determine inband FEC, maximum
2154 // playback rate, and opus internal dtx.
2155 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002156 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01002157 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002158 }
Brave Yao5225dd82015-03-26 07:39:19 +08002159
2160 // Set packet size if the AudioCodec param kCodecParamPTime is set.
2161 int ptime_ms = 0;
2162 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
2163 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2164 LOG(LS_WARNING) << "Failed to set packet size for codec "
2165 << send_codec.plname;
2166 return false;
2167 }
2168 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002169 }
2170 found_send_codec = true;
2171 break;
2172 }
2173
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002174 if (nack_enabled_ != nack_enabled) {
2175 SetNack(channel, nack_enabled);
2176 nack_enabled_ = nack_enabled;
2177 }
2178
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002179 if (!found_send_codec) {
2180 LOG(LS_WARNING) << "Received empty list of codecs.";
2181 return false;
2182 }
2183
2184 // Set the codec immediately, since SetVADStatus() depends on whether
2185 // the current codec is mono or stereo.
2186 if (!SetSendCodec(channel, send_codec))
2187 return false;
2188
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002189 // FEC should be enabled after SetSendCodec.
2190 if (enable_codec_fec) {
2191 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2192 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002193 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2194 // Enable codec internal FEC. Treat any failure as fatal internal error.
2195 LOG_RTCERR2(SetFECStatus, channel, true);
2196 return false;
2197 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002198 }
2199
Minyue Li7100dcd2015-03-27 05:05:59 +01002200 if (IsCodec(send_codec, kOpusCodecName)) {
2201 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2202 // send codec has to be Opus.
2203
2204 // Set Opus internal DTX.
2205 LOG(LS_INFO) << "Attempt to "
2206 << GetEnableString(enable_opus_dtx)
2207 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002208 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002209 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2210 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2211 return false;
2212 }
2213
2214 // If opus_max_playback_rate <= 0, the default maximum playback rate
2215 // (48 kHz) will be used.
2216 if (opus_max_playback_rate > 0) {
2217 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2218 << opus_max_playback_rate
2219 << " Hz on channel "
2220 << channel;
2221 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2222 channel, opus_max_playback_rate) == -1) {
2223 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2224 return false;
2225 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002226 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002227 }
2228
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002229 // Always update the |send_codec_| to the currently set send codec.
2230 send_codec_.reset(new webrtc::CodecInst(send_codec));
2231
minyue@webrtc.org26236952014-10-29 02:27:08 +00002232 if (send_bitrate_setting_) {
2233 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002234 }
2235
2236 // Loop through the codecs list again to config the telephone-event/CN codec.
2237 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2238 it != codecs.end(); ++it) {
2239 // Ignore codecs we don't know about. The negotiation step should prevent
2240 // this, but double-check to be sure.
2241 webrtc::CodecInst voe_codec;
2242 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2243 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2244 continue;
2245 }
2246
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002247 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2248 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002249 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002250 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2251 channel, it->id) == -1) {
2252 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2253 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002255 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002256 // Turn voice activity detection/comfort noise on if supported.
2257 // Set the wideband CN payload type appropriately.
2258 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 webrtc::PayloadFrequencies cn_freq;
2260 switch (it->clockrate) {
2261 case 8000:
2262 cn_freq = webrtc::kFreq8000Hz;
2263 break;
2264 case 16000:
2265 cn_freq = webrtc::kFreq16000Hz;
2266 break;
2267 case 32000:
2268 cn_freq = webrtc::kFreq32000Hz;
2269 break;
2270 default:
2271 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2272 << " not supported.";
2273 continue;
2274 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002275 // Set the CN payloadtype and the VAD status.
2276 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2277 if (cn_freq != webrtc::kFreq8000Hz) {
2278 if (engine()->voe()->codec()->SetSendCNPayloadType(
2279 channel, it->id, cn_freq) == -1) {
2280 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2281 // TODO(ajm): This failure condition will be removed from VoE.
2282 // Restore the return here when we update to a new enough webrtc.
2283 //
2284 // Not returning false because the SetSendCNPayloadType will fail if
2285 // the channel is already sending.
2286 // This can happen if the remote description is applied twice, for
2287 // example in the case of ROAP on top of JSEP, where both side will
2288 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002290 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002291 // Only turn on VAD if we have a CN payload type that matches the
2292 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002293 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2294 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2295 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002296 LOG(LS_INFO) << "Enabling VAD";
2297 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2298 LOG_RTCERR2(SetVADStatus, channel, true);
2299 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 }
2301 }
2302 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002303 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002304 return true;
2305}
2306
2307bool WebRtcVoiceMediaChannel::SetSendCodecs(
2308 const std::vector<AudioCodec>& codecs) {
2309 dtmf_allowed_ = false;
2310 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2311 it != codecs.end(); ++it) {
2312 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002313 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002314 dtmf_allowed_ = true;
2315 }
2316 }
2317
2318 // Cache the codecs in order to configure the channel created later.
2319 send_codecs_ = codecs;
2320 for (ChannelMap::iterator iter = send_channels_.begin();
2321 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002322 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002323 return false;
2324 }
2325 }
2326
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002327 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002328 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 return true;
2330}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002331
2332void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2333 bool nack_enabled) {
2334 for (ChannelMap::const_iterator it = channels.begin();
2335 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002336 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002337 }
2338}
2339
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002340void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002342 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002343 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2344 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002345 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2347 }
2348}
2349
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350bool WebRtcVoiceMediaChannel::SetSendCodec(
2351 const webrtc::CodecInst& send_codec) {
2352 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2353 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002354 for (ChannelMap::iterator iter = send_channels_.begin();
2355 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002356 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002357 return false;
2358 }
2359
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002360 return true;
2361}
2362
2363bool WebRtcVoiceMediaChannel::SetSendCodec(
2364 int channel, const webrtc::CodecInst& send_codec) {
2365 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2366 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2367
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002368 webrtc::CodecInst current_codec;
2369 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2370 (send_codec == current_codec)) {
2371 // Codec is already configured, we can return without setting it again.
2372 return true;
2373 }
2374
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002375 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2376 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 return false;
2378 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 return true;
2380}
2381
2382bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2383 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002384 if (receive_extensions_ == extensions) {
2385 return true;
2386 }
2387
2388 // The default channel may or may not be in |receive_channels_|. Set the rtp
2389 // header extensions for default channel regardless.
2390 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2391 return false;
2392 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002393
2394 // Loop through all receive channels and enable/disable the extensions.
2395 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2396 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002397 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2398 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002399 return false;
2400 }
2401 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002402
2403 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002404
2405 // Recreate AudioReceiveStream:s.
2406 {
2407 std::vector<webrtc::RtpExtension> exts;
2408
2409 const RtpHeaderExtension* audio_level_extension =
2410 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2411 if (audio_level_extension) {
2412 exts.push_back({
2413 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2414 }
2415
2416 const RtpHeaderExtension* send_time_extension =
2417 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2418 if (send_time_extension) {
2419 exts.push_back({
2420 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2421 }
2422
2423 recv_rtp_extensions_.swap(exts);
2424 SetCall(call_);
2425 }
2426
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002427 return true;
2428}
2429
2430bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2431 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002432 const RtpHeaderExtension* audio_level_extension =
2433 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2434 if (!SetHeaderExtension(
2435 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2436 audio_level_extension)) {
2437 return false;
2438 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002439
2440 const RtpHeaderExtension* send_time_extension =
2441 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2442 if (!SetHeaderExtension(
2443 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2444 send_time_extension)) {
2445 return false;
2446 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002447
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 return true;
2449}
2450
2451bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2452 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002453 if (send_extensions_ == extensions) {
2454 return true;
2455 }
2456
2457 // The default channel may or may not be in |send_channels_|. Set the rtp
2458 // header extensions for default channel regardless.
2459
2460 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2461 return false;
2462 }
2463
2464 // Loop through all send channels and enable/disable the extensions.
2465 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2466 channel_it != send_channels_.end(); ++channel_it) {
2467 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2468 extensions)) {
2469 return false;
2470 }
2471 }
2472
2473 send_extensions_ = extensions;
2474 return true;
2475}
2476
2477bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2478 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002479 const RtpHeaderExtension* audio_level_extension =
2480 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002481
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002482 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002483 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002484 audio_level_extension)) {
2485 return false;
2486 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002487
2488 const RtpHeaderExtension* send_time_extension =
2489 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002490 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002491 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002492 send_time_extension)) {
2493 return false;
2494 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 return true;
2497}
2498
2499bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2500 desired_playout_ = playout;
2501 return ChangePlayout(desired_playout_);
2502}
2503
2504bool WebRtcVoiceMediaChannel::PausePlayout() {
2505 return ChangePlayout(false);
2506}
2507
2508bool WebRtcVoiceMediaChannel::ResumePlayout() {
2509 return ChangePlayout(desired_playout_);
2510}
2511
2512bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2513 if (playout_ == playout) {
2514 return true;
2515 }
2516
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002517 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002519 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 // Only toggle the default channel if we don't have any other channels.
2521 result = SetPlayout(voe_channel(), playout);
2522 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002523 for (ChannelMap::iterator it = receive_channels_.begin();
2524 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002525 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002526 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002527 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 result = false;
2529 }
2530 }
2531
2532 if (result) {
2533 playout_ = playout;
2534 }
2535 return result;
2536}
2537
2538bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2539 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002540 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002541 return ChangeSend(desired_send_);
2542 return true;
2543}
2544
2545bool WebRtcVoiceMediaChannel::PauseSend() {
2546 return ChangeSend(SEND_NOTHING);
2547}
2548
2549bool WebRtcVoiceMediaChannel::ResumeSend() {
2550 return ChangeSend(desired_send_);
2551}
2552
2553bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2554 if (send_ == send) {
2555 return true;
2556 }
2557
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002558 // Change the settings on each send channel.
2559 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560 engine()->SetOptionOverrides(options_);
2561
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002562 // Change the settings on each send channel.
2563 for (ChannelMap::iterator iter = send_channels_.begin();
2564 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002565 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002567 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002568
2569 // Clear up the options after stopping sending.
2570 if (send == SEND_NOTHING)
2571 engine()->ClearOptionOverrides();
2572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 send_ = send;
2574 return true;
2575}
2576
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002577bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2578 if (send == SEND_MICROPHONE) {
2579 if (engine()->voe()->base()->StartSend(channel) == -1) {
2580 LOG_RTCERR1(StartSend, channel);
2581 return false;
2582 }
2583 if (engine()->voe()->file() &&
2584 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2585 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2586 return false;
2587 }
2588 } else { // SEND_NOTHING
2589 ASSERT(send == SEND_NOTHING);
2590 if (engine()->voe()->base()->StopSend(channel) == -1) {
2591 LOG_RTCERR1(StopSend, channel);
2592 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 }
2594 }
2595
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596 return true;
2597}
2598
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002599// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002600void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2601 if (engine()->voe()->network()->RegisterExternalTransport(
2602 channel, *this) == -1) {
2603 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2604 }
2605
2606 // Enable RTCP (for quality stats and feedback messages)
2607 EnableRtcp(channel);
2608
2609 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2610 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002611
2612 // Set RTP header extension for the new channel.
2613 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002614}
2615
2616bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2617 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2618 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2619 }
2620
2621 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2622 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002623 return false;
2624 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002625
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626 return true;
2627}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002628
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002629bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2630 // If the default channel is already used for sending create a new channel
2631 // otherwise use the default channel for sending.
2632 int channel = GetSendChannelNum(sp.first_ssrc());
2633 if (channel != -1) {
2634 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2635 return false;
2636 }
2637
2638 bool default_channel_is_available = true;
2639 for (ChannelMap::const_iterator iter = send_channels_.begin();
2640 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002641 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002642 default_channel_is_available = false;
2643 break;
2644 }
2645 }
2646 if (default_channel_is_available) {
2647 channel = voe_channel();
2648 } else {
2649 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002650 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002651 if (channel == -1) {
2652 LOG_RTCERR0(CreateChannel);
2653 return false;
2654 }
2655
2656 ConfigureSendChannel(channel);
2657 }
2658
2659 // Save the channel to send_channels_, so that RemoveSendStream() can still
2660 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002661 webrtc::AudioTransport* audio_transport =
2662 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002663 send_channels_.insert(std::make_pair(
2664 sp.first_ssrc(),
2665 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002666
2667 // Set the send (local) SSRC.
2668 // If there are multiple send SSRCs, we can only set the first one here, and
2669 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2670 // (with a codec requires multiple SSRC(s)).
2671 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2672 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2673 return false;
2674 }
2675
2676 // At this point the channel's local SSRC has been updated. If the channel is
2677 // the default channel make sure that all the receive channels are updated as
2678 // well. Receive channels have to have the same SSRC as the default channel in
2679 // order to send receiver reports with this SSRC.
2680 if (IsDefaultChannel(channel)) {
2681 for (ChannelMap::const_iterator it = receive_channels_.begin();
2682 it != receive_channels_.end(); ++it) {
2683 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002684 if (!IsDefaultChannel(it->second->channel())) {
2685 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002686 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002687 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002688 return false;
2689 }
2690 }
2691 }
2692 }
2693
2694 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002695 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2696 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002697 }
2698
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002699 // Set the current codecs to be used for the new channel.
2700 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002701 return false;
2702
2703 return ChangeSend(channel, desired_send_);
2704}
2705
2706bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2707 ChannelMap::iterator it = send_channels_.find(ssrc);
2708 if (it == send_channels_.end()) {
2709 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2710 << " which doesn't exist.";
2711 return false;
2712 }
2713
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002714 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002715 ChangeSend(channel, SEND_NOTHING);
2716
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002717 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2718 // this will disconnect the audio renderer with the send channel.
2719 delete it->second;
2720 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002721
2722 if (IsDefaultChannel(channel)) {
2723 // Do not delete the default channel since the receive channels depend on
2724 // the default channel, recycle it instead.
2725 ChangeSend(channel, SEND_NOTHING);
2726 } else {
2727 // Clean up and delete the send channel.
2728 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2729 << " with VoiceEngine channel #" << channel << ".";
2730 if (!DeleteChannel(channel))
2731 return false;
2732 }
2733
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002734 if (send_channels_.empty())
2735 ChangeSend(SEND_NOTHING);
2736
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 return true;
2738}
2739
2740bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002741 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002742 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743
2744 if (!VERIFY(sp.ssrcs.size() == 1))
2745 return false;
2746 uint32 ssrc = sp.first_ssrc();
2747
wu@webrtc.org78187522013-10-07 23:32:02 +00002748 if (ssrc == 0) {
2749 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2750 return false;
2751 }
2752
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002753 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2754 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755 return false;
2756 }
2757
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002758 TryAddAudioRecvStream(ssrc);
2759
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002760 // Reuse default channel for recv stream in non-conference mode call
2761 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002762 webrtc::AudioTransport* audio_transport =
2763 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002764 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002765 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2766 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002768 default_receive_ssrc_,
2769 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002770 if (!SetupSharedBweOnChannel(voe_channel())) {
2771 return false;
2772 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002773 return SetPlayout(voe_channel(), playout_);
2774 }
2775
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002777 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778 if (channel == -1) {
2779 LOG_RTCERR0(CreateChannel);
2780 return false;
2781 }
2782
wu@webrtc.org78187522013-10-07 23:32:02 +00002783 if (!ConfigureRecvChannel(channel)) {
2784 DeleteChannel(channel);
2785 return false;
2786 }
2787
2788 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002789 std::make_pair(
2790 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002791
2792 LOG(LS_INFO) << "New audio stream " << ssrc
2793 << " registered to VoiceEngine channel #"
2794 << channel << ".";
2795 return true;
2796}
2797
2798bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799 // Configure to use external transport, like our default channel.
2800 if (engine()->voe()->network()->RegisterExternalTransport(
2801 channel, *this) == -1) {
2802 LOG_RTCERR2(SetExternalTransport, channel, this);
2803 return false;
2804 }
2805
2806 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002807 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2809 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002810 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811 return false;
2812 }
2813 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002814 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002815 return false;
2816 }
2817
2818 // Use the same recv payload types as our default channel.
2819 ResetRecvCodecs(channel);
2820 if (!recv_codecs_.empty()) {
2821 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2822 it != recv_codecs_.end(); ++it) {
2823 webrtc::CodecInst voe_codec;
2824 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2825 voe_codec.pltype = it->id;
2826 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2827 if (engine()->voe()->codec()->GetRecPayloadType(
2828 voe_channel(), voe_codec) != -1) {
2829 if (engine()->voe()->codec()->SetRecPayloadType(
2830 channel, voe_codec) == -1) {
2831 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2832 return false;
2833 }
2834 }
2835 }
2836 }
2837 }
2838
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002839 if (InConferenceMode()) {
2840 // To be in par with the video, voe_channel() is not used for receiving in
2841 // a conference call.
2842 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2843 // This is the first stream in a multi user meeting. We can now
2844 // disable playback of the default stream. This since the default
2845 // stream will probably have received some initial packets before
2846 // the new stream was added. This will mean that the CN state from
2847 // the default channel will be mixed in with the other streams
2848 // throughout the whole meeting, which might be disturbing.
2849 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2850 SetPlayout(voe_channel(), false);
2851 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002853 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002855 // Set RTP header extension for the new channel.
2856 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2857 return false;
2858 }
2859
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002860 // Set up channel to be able to forward incoming packets to video engine BWE.
2861 if (!SetupSharedBweOnChannel(channel)) {
2862 return false;
2863 }
2864
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 return SetPlayout(channel, playout_);
2866}
2867
2868bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002869 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002870 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002871 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002872 if (it == receive_channels_.end()) {
2873 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2874 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002875 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002876 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002878 TryRemoveAudioRecvStream(ssrc);
2879
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002880 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2881 // will disconnect the audio renderer with the receive channel.
2882 // Cache the channel before the deletion.
2883 const int channel = it->second->channel();
2884 delete it->second;
2885 receive_channels_.erase(it);
2886
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002887 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002888 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002889 // Recycle the default channel is for recv stream.
2890 if (playout_)
2891 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002892
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002893 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002894 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002897 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002898 << " with VoiceEngine channel #" << channel << ".";
2899 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002900 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002901
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002902 bool enable_default_channel_playout = false;
2903 if (receive_channels_.empty()) {
2904 // The last stream was removed. We can now enable the default
2905 // channel for new channels to be played out immediately without
2906 // waiting for AddStream messages.
2907 // We do this for both conference mode and non-conference mode.
2908 // TODO(oja): Does the default channel still have it's CN state?
2909 enable_default_channel_playout = true;
2910 }
2911 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2912 default_receive_ssrc_ != 0) {
2913 // Only the default channel is active, enable the playout on default
2914 // channel.
2915 enable_default_channel_playout = true;
2916 }
2917 if (enable_default_channel_playout && playout_) {
2918 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2919 SetPlayout(voe_channel(), true);
2920 }
2921
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 return true;
2923}
2924
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002925bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2926 AudioRenderer* renderer) {
2927 ChannelMap::iterator it = receive_channels_.find(ssrc);
2928 if (it == receive_channels_.end()) {
2929 if (renderer) {
2930 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002931 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002932 return false;
2933 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002934
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002935 // The channel likely has gone away, do nothing.
2936 return true;
2937 }
2938
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002939 if (renderer)
2940 it->second->Start(renderer);
2941 else
2942 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002943
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002944 return true;
2945}
2946
2947bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2948 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002949 ChannelMap::iterator it = send_channels_.find(ssrc);
2950 if (it == send_channels_.end()) {
2951 if (renderer) {
2952 // Return an error if trying to set a valid renderer with an invalid ssrc.
2953 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2954 return false;
2955 }
2956
2957 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002958 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002959 }
2960
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002961 if (renderer)
2962 it->second->Start(renderer);
2963 else
2964 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966 return true;
2967}
2968
2969bool WebRtcVoiceMediaChannel::GetActiveStreams(
2970 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002971 // In conference mode, the default channel should not be in
2972 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002973 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002974 for (ChannelMap::iterator it = receive_channels_.begin();
2975 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002976 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977 if (level > 0) {
2978 actives->push_back(std::make_pair(it->first, level));
2979 }
2980 }
2981 return true;
2982}
2983
2984int WebRtcVoiceMediaChannel::GetOutputLevel() {
2985 // return the highest output level of all streams
2986 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002987 for (ChannelMap::iterator it = receive_channels_.begin();
2988 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002989 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002990 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002991 }
2992 return highest;
2993}
2994
2995int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2996 int ret;
2997 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2998 // In case of error, log the info and continue
2999 LOG_RTCERR0(TimeSinceLastTyping);
3000 ret = -1;
3001 } else {
3002 ret *= 1000; // We return ms, webrtc returns seconds.
3003 }
3004 return ret;
3005}
3006
3007void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
3008 int cost_per_typing, int reporting_threshold, int penalty_decay,
3009 int type_event_delay) {
3010 if (engine()->voe()->processing()->SetTypingDetectionParameters(
3011 time_window, cost_per_typing,
3012 reporting_threshold, penalty_decay, type_event_delay) == -1) {
3013 // In case of error, log the info and continue
3014 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
3015 cost_per_typing, reporting_threshold, penalty_decay,
3016 type_event_delay);
3017 }
3018}
3019
3020bool WebRtcVoiceMediaChannel::SetOutputScaling(
3021 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003022 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 // Collect the channels to scale the output volume.
3024 std::vector<int> channels;
3025 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003026 // Default channel is not in receive_channels_ if it is not being used for
3027 // playout.
3028 if (default_receive_ssrc_ == 0)
3029 channels.push_back(voe_channel());
3030 for (ChannelMap::const_iterator it = receive_channels_.begin();
3031 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003032 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 }
3034 } else { // Collect only the channel of the specified ssrc.
3035 int channel = GetReceiveChannelNum(ssrc);
3036 if (-1 == channel) {
3037 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3038 return false;
3039 }
3040 channels.push_back(channel);
3041 }
3042
3043 // Scale the output volume for the collected channels. We first normalize to
3044 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00003045 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003046 if (scale > 0.0001f) {
3047 left /= scale;
3048 right /= scale;
3049 }
3050 for (std::vector<int>::const_iterator it = channels.begin();
3051 it != channels.end(); ++it) {
3052 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
3053 *it, scale)) {
3054 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
3055 return false;
3056 }
3057 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
3058 *it, static_cast<float>(left), static_cast<float>(right))) {
3059 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
3060 // Do not return if fails. SetOutputVolumePan is not available for all
3061 // pltforms.
3062 }
3063 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
3064 << " right=" << right * scale
3065 << " for channel " << *it << " and ssrc " << ssrc;
3066 }
3067 return true;
3068}
3069
3070bool WebRtcVoiceMediaChannel::GetOutputScaling(
3071 uint32 ssrc, double* left, double* right) {
3072 if (!left || !right) return false;
3073
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003074 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 // Determine which channel based on ssrc.
3076 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3077 if (channel == -1) {
3078 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3079 return false;
3080 }
3081
3082 float scaling;
3083 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3084 channel, scaling)) {
3085 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3086 return false;
3087 }
3088
3089 float left_pan;
3090 float right_pan;
3091 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3092 channel, left_pan, right_pan)) {
3093 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3094 // If GetOutputVolumePan fails, we use the default left and right pan.
3095 left_pan = 1.0f;
3096 right_pan = 1.0f;
3097 }
3098
3099 *left = scaling * left_pan;
3100 *right = scaling * right_pan;
3101 return true;
3102}
3103
3104bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3105 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3106 return true;
3107}
3108
3109bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3110 bool play, bool loop) {
3111 if (!ringback_tone_) {
3112 return false;
3113 }
3114
3115 // The voe file api is not available in chrome.
3116 if (!engine()->voe()->file()) {
3117 return false;
3118 }
3119
3120 // Determine which VoiceEngine channel to play on.
3121 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3122 if (channel == -1) {
3123 return false;
3124 }
3125
3126 // Make sure the ringtone is cued properly, and play it out.
3127 if (play) {
3128 ringback_tone_->set_loop(loop);
3129 ringback_tone_->Rewind();
3130 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3131 ringback_tone_.get()) == -1) {
3132 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3133 LOG(LS_ERROR) << "Unable to start ringback tone";
3134 return false;
3135 }
3136 ringback_channels_.insert(channel);
3137 LOG(LS_INFO) << "Started ringback on channel " << channel;
3138 } else {
3139 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3140 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3141 LOG_RTCERR1(StopPlayingFileLocally, channel);
3142 return false;
3143 }
3144 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3145 ringback_channels_.erase(channel);
3146 }
3147
3148 return true;
3149}
3150
3151bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3152 return dtmf_allowed_;
3153}
3154
3155bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3156 int duration, int flags) {
3157 if (!dtmf_allowed_) {
3158 return false;
3159 }
3160
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161 // Send the event.
3162 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003163 int channel = -1;
3164 if (ssrc == 0) {
3165 bool default_channel_is_inuse = false;
3166 for (ChannelMap::const_iterator iter = send_channels_.begin();
3167 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003168 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003169 default_channel_is_inuse = true;
3170 break;
3171 }
3172 }
3173 if (default_channel_is_inuse) {
3174 channel = voe_channel();
3175 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003176 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003177 }
3178 } else {
3179 channel = GetSendChannelNum(ssrc);
3180 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003181 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3183 << ssrc << " is not in use.";
3184 return false;
3185 }
3186 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003187 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3188 channel, event, true, duration) == -1) {
3189 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 return false;
3191 }
3192 }
3193
3194 // Play the event.
3195 if (flags & cricket::DF_PLAY) {
3196 // Play DTMF tone locally.
3197 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3198 LOG_RTCERR2(PlayDtmfTone, event, duration);
3199 return false;
3200 }
3201 }
3202
3203 return true;
3204}
3205
wu@webrtc.orga9890802013-12-13 00:21:03 +00003206void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003207 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003208 DCHECK(thread_checker_.CalledOnValidThread());
3209
3210 // If hooked up to a "Call", forward packet there too.
3211 if (call_) {
3212 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3213 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3214 }
3215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 // Pick which channel to send this packet to. If this packet doesn't match
3217 // any multiplexed streams, just send it to the default channel. Otherwise,
3218 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003219 int which_channel =
3220 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003221 if (which_channel == -1) {
3222 which_channel = voe_channel();
3223 }
3224
3225 // Stop any ringback that might be playing on the channel.
3226 // It's possible the ringback has already stopped, ih which case we'll just
3227 // use the opportunity to remove the channel from ringback_channels_.
3228 if (engine()->voe()->file()) {
3229 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3230 if (it != ringback_channels_.end()) {
3231 if (engine()->voe()->file()->IsPlayingFileLocally(
3232 which_channel) == 1) {
3233 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3234 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3235 << " due to incoming media";
3236 }
3237 ringback_channels_.erase(which_channel);
3238 }
3239 }
3240
3241 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003242 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003243 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003244 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003245}
3246
wu@webrtc.orga9890802013-12-13 00:21:03 +00003247void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003248 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003249 DCHECK(thread_checker_.CalledOnValidThread());
3250
3251 // If hooked up to a "Call", forward packet there too.
3252 if (call_) {
3253 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3254 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3255 }
3256
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003257 // Sending channels need all RTCP packets with feedback information.
3258 // Even sender reports can contain attached report blocks.
3259 // Receiving channels need sender reports in order to create
3260 // correct receiver reports.
3261 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003262 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003263 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3264 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265 }
3266
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003267 // If it is a sender report, find the channel that is listening.
3268 bool has_sent_to_default_channel = false;
3269 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003270 int which_channel =
3271 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003272 if (which_channel != -1) {
3273 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003274 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003275
3276 if (IsDefaultChannel(which_channel))
3277 has_sent_to_default_channel = true;
3278 }
3279 }
3280
3281 // SR may continue RR and any RR entry may correspond to any one of the send
3282 // channels. So all RTCP packets must be forwarded all send channels. VoE
3283 // will filter out RR internally.
3284 for (ChannelMap::iterator iter = send_channels_.begin();
3285 iter != send_channels_.end(); ++iter) {
3286 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003287 if (IsDefaultChannel(iter->second->channel()) &&
3288 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003289 continue;
3290
3291 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003292 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003293 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003294}
3295
3296bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003297 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3298 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3300 return false;
3301 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003302 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3303 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003304 return false;
3305 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003306 // We set the AGC to mute state only when all the channels are muted.
3307 // This implementation is not ideal, instead we should signal the AGC when
3308 // the mic channel is muted/unmuted. We can't do it today because there
3309 // is no good way to know which stream is mapping to the mic channel.
3310 bool all_muted = muted;
3311 for (ChannelMap::const_iterator iter = send_channels_.begin();
3312 iter != send_channels_.end() && all_muted; ++iter) {
3313 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3314 all_muted)) {
3315 LOG_RTCERR1(GetInputMute, iter->second->channel());
3316 return false;
3317 }
3318 }
3319
3320 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3321 if (ap)
3322 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323 return true;
3324}
3325
minyue@webrtc.org26236952014-10-29 02:27:08 +00003326// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3327// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003328bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003329 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003330
minyue@webrtc.org26236952014-10-29 02:27:08 +00003331 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003332}
3333
minyue@webrtc.org26236952014-10-29 02:27:08 +00003334bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3335 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003336
minyue@webrtc.org26236952014-10-29 02:27:08 +00003337 send_bitrate_setting_ = true;
3338 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003339
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003341 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003342 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003343 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003344 }
3345
minyue@webrtc.org26236952014-10-29 02:27:08 +00003346 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003347 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3348 // SetMaxSendBandwith(0), the second call removes the previous limit.
3349 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 return true;
3351
3352 webrtc::CodecInst codec = *send_codec_;
3353 bool is_multi_rate = IsCodecMultiRate(codec);
3354
3355 if (is_multi_rate) {
3356 // If codec is multi-rate then just set the bitrate.
3357 codec.rate = bps;
3358 if (!SetSendCodec(codec)) {
3359 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3360 << " to bitrate " << bps << " bps.";
3361 return false;
3362 }
3363 return true;
3364 } else {
3365 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3366 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3367 // fixed bitrate then ignore.
3368 if (bps < codec.rate) {
3369 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3370 << " to bitrate " << bps << " bps"
3371 << ", requires at least " << codec.rate << " bps.";
3372 return false;
3373 }
3374 return true;
3375 }
3376}
3377
3378bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003379 bool echo_metrics_on = false;
3380 // These can take on valid negative values, so use the lowest possible level
3381 // as default rather than -1.
3382 int echo_return_loss = -100;
3383 int echo_return_loss_enhancement = -100;
3384 // These can also be negative, but in practice -1 is only used to signal
3385 // insufficient data, since the resolution is limited to multiples of 4 ms.
3386 int echo_delay_median_ms = -1;
3387 int echo_delay_std_ms = -1;
3388 if (engine()->voe()->processing()->GetEcMetricsStatus(
3389 echo_metrics_on) != -1 && echo_metrics_on) {
3390 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3391 // here, but it appears to be unsuitable currently. Revisit after this is
3392 // investigated: http://b/issue?id=5666755
3393 int erl, erle, rerl, anlp;
3394 if (engine()->voe()->processing()->GetEchoMetrics(
3395 erl, erle, rerl, anlp) != -1) {
3396 echo_return_loss = erl;
3397 echo_return_loss_enhancement = erle;
3398 }
3399
3400 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003401 float dummy;
3402 if (engine()->voe()->processing()->GetEcDelayMetrics(
3403 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003404 echo_delay_median_ms = median;
3405 echo_delay_std_ms = std;
3406 }
3407 }
3408
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003409 webrtc::CallStatistics cs;
3410 unsigned int ssrc;
3411 webrtc::CodecInst codec;
3412 unsigned int level;
3413
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003414 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3415 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003416 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003418 // Fill in the sender info, based on what we know, and what the
3419 // remote side told us it got from its RTCP report.
3420 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003421
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003422 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3423 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3424 continue;
3425 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003427 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003428 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3429 sinfo.bytes_sent = cs.bytesSent;
3430 sinfo.packets_sent = cs.packetsSent;
3431 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3432 // returns 0 to indicate an error value.
3433 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3434
3435 // Get data from the last remote RTCP report. Use default values if no data
3436 // available.
3437 sinfo.fraction_lost = -1.0;
3438 sinfo.jitter_ms = -1;
3439 sinfo.packets_lost = -1;
3440 sinfo.ext_seqnum = -1;
3441 std::vector<webrtc::ReportBlock> receive_blocks;
3442 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3443 channel, &receive_blocks) != -1 &&
3444 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3445 std::vector<webrtc::ReportBlock>::iterator iter;
3446 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3447 ++iter) {
3448 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003449 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003450 // Convert Q8 to floating point.
3451 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3452 // Convert samples to milliseconds.
3453 if (codec.plfreq / 1000 > 0) {
3454 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3455 }
3456 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3457 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3458 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003459 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460 }
3461 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003462
3463 // Local speech level.
3464 sinfo.audio_level = (engine()->voe()->volume()->
3465 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3466
3467 // TODO(xians): We are injecting the same APM logging to all the send
3468 // channels here because there is no good way to know which send channel
3469 // is using the APM. The correct fix is to allow the send channels to have
3470 // their own APM so that we can feed the correct APM logging to different
3471 // send channels. See issue crbug/264611 .
3472 sinfo.echo_return_loss = echo_return_loss;
3473 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3474 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3475 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003476 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3477 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003478 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003479
3480 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481 }
3482
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003483 // Build the list of receivers, one for each receiving channel, or 1 in
3484 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003486 for (ChannelMap::const_iterator it = receive_channels_.begin();
3487 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003488 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489 }
3490 if (channels.empty()) {
3491 channels.push_back(voe_channel());
3492 }
3493
3494 // Get the SSRC and stats for each receiver, based on our own calculations.
3495 for (std::vector<int>::const_iterator it = channels.begin();
3496 it != channels.end(); ++it) {
3497 memset(&cs, 0, sizeof(cs));
3498 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3499 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3500 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3501 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003502 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003503 rinfo.bytes_rcvd = cs.bytesReceived;
3504 rinfo.packets_rcvd = cs.packetsReceived;
3505 // The next four fields are from the most recently sent RTCP report.
3506 // Convert Q8 to floating point.
3507 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3508 rinfo.packets_lost = cs.cumulativeLost;
3509 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003510 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003511 if (codec.pltype != -1) {
3512 rinfo.codec_name = codec.plname;
3513 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003514 // Convert samples to milliseconds.
3515 if (codec.plfreq / 1000 > 0) {
3516 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3517 }
3518
3519 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3520 webrtc::NetworkStatistics ns;
3521 if (engine()->voe()->neteq() &&
3522 engine()->voe()->neteq()->GetNetworkStatistics(
3523 *it, ns) != -1) {
3524 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3525 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3526 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003527 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003528 rinfo.speech_expand_rate =
3529 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3530 rinfo.secondary_decoded_rate =
3531 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003532 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003533
3534 webrtc::AudioDecodingCallStats ds;
3535 if (engine()->voe()->neteq() &&
3536 engine()->voe()->neteq()->GetDecodingCallStatistics(
3537 *it, &ds) != -1) {
3538 rinfo.decoding_calls_to_silence_generator =
3539 ds.calls_to_silence_generator;
3540 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3541 rinfo.decoding_normal = ds.decoded_normal;
3542 rinfo.decoding_plc = ds.decoded_plc;
3543 rinfo.decoding_cng = ds.decoded_cng;
3544 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3545 }
3546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003548 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549 int playout_buffer_delay_ms = 0;
3550 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003551 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3552 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3553 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003554 }
3555
3556 // Get speech level.
3557 rinfo.audio_level = (engine()->voe()->volume()->
3558 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3559 info->receivers.push_back(rinfo);
3560 }
3561 }
3562
3563 return true;
3564}
3565
3566void WebRtcVoiceMediaChannel::GetLastMediaError(
3567 uint32* ssrc, VoiceMediaChannel::Error* error) {
3568 ASSERT(ssrc != NULL);
3569 ASSERT(error != NULL);
3570 FindSsrc(voe_channel(), ssrc);
3571 *error = WebRtcErrorToChannelError(GetLastEngineError());
3572}
3573
3574bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003575 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003576 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003577 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003578 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3579 // This means the error is not limited to a specific channel. Signal the
3580 // message using ssrc=0. If the current channel is sending, use this
3581 // channel for sending the message.
3582 *ssrc = 0;
3583 return true;
3584 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003585 // Check whether this is a sending channel.
3586 for (ChannelMap::const_iterator it = send_channels_.begin();
3587 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003588 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003589 // This is a sending channel.
3590 uint32 local_ssrc = 0;
3591 if (engine()->voe()->rtp()->GetLocalSSRC(
3592 channel_num, local_ssrc) != -1) {
3593 *ssrc = local_ssrc;
3594 }
3595 return true;
3596 }
3597 }
3598
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003599 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003600 for (ChannelMap::const_iterator it = receive_channels_.begin();
3601 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003602 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003603 *ssrc = it->first;
3604 return true;
3605 }
3606 }
3607 }
3608 return false;
3609}
3610
3611void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003612 if (error == VE_TYPING_NOISE_WARNING) {
3613 typing_noise_detected_ = true;
3614 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3615 typing_noise_detected_ = false;
3616 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003617 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3618}
3619
3620int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3621 unsigned int ulevel;
3622 int ret =
3623 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3624 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3625}
3626
3627int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003628 ChannelMap::iterator it = receive_channels_.find(ssrc);
3629 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003630 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003631 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3632}
3633
3634int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003635 ChannelMap::iterator it = send_channels_.find(ssrc);
3636 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003637 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003638
3639 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003640}
3641
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003642bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3643 webrtc::VideoEngine* vie, int vie_channel) {
3644 shared_bwe_vie_ = vie;
3645 shared_bwe_vie_channel_ = vie_channel;
3646
3647 if (!SetupSharedBweOnChannel(voe_channel())) {
3648 return false;
3649 }
3650 for (ChannelMap::iterator it = receive_channels_.begin();
3651 it != receive_channels_.end(); ++it) {
3652 if (!SetupSharedBweOnChannel(it->second->channel())) {
3653 return false;
3654 }
3655 }
3656 return true;
3657}
3658
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003659void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3660 DCHECK(thread_checker_.CalledOnValidThread());
3661 DCHECK(!call || !shared_bwe_vie_);
3662 DCHECK(!call || shared_bwe_vie_channel_ == -1);
3663
3664 for (const auto& it : receive_channels_) {
3665 TryRemoveAudioRecvStream(it.first);
3666 }
3667
3668 call_ = call;
3669
3670 for (const auto& it : receive_channels_) {
3671 TryAddAudioRecvStream(it.first);
3672 }
3673}
3674
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003675bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3676 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3677 // Get the RED encodings from the parameter with no name. This may
3678 // change based on what is discussed on the Jingle list.
3679 // The encoding parameter is of the form "a/b"; we only support where
3680 // a == b. Verify this and parse out the value into red_pt.
3681 // If the parameter value is absent (as it will be until we wire up the
3682 // signaling of this message), use the second codec specified (i.e. the
3683 // one after "red") as the encoding parameter.
3684 int red_pt = -1;
3685 std::string red_params;
3686 CodecParameterMap::const_iterator it = red_codec.params.find("");
3687 if (it != red_codec.params.end()) {
3688 red_params = it->second;
3689 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003690 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003691 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003692 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003693 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3694 return false;
3695 }
3696 } else if (red_codec.params.empty()) {
3697 LOG(LS_WARNING) << "RED params not present, using defaults";
3698 if (all_codecs.size() > 1) {
3699 red_pt = all_codecs[1].id;
3700 }
3701 }
3702
3703 // Try to find red_pt in |codecs|.
3704 std::vector<AudioCodec>::const_iterator codec;
3705 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3706 if (codec->id == red_pt)
3707 break;
3708 }
3709
3710 // If we find the right codec, that will be the codec we pass to
3711 // SetSendCodec, with the desired payload type.
3712 if (codec != all_codecs.end() &&
3713 engine()->FindWebRtcCodec(*codec, send_codec)) {
3714 } else {
3715 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3716 return false;
3717 }
3718
3719 return true;
3720}
3721
3722bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3723 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003724 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003725 return false;
3726 }
3727 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3728 // what we want to do with them.
3729 // engine()->voe().EnableVQMon(voe_channel(), true);
3730 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3731 return true;
3732}
3733
3734bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3735 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3736 for (int i = 0; i < ncodecs; ++i) {
3737 webrtc::CodecInst voe_codec;
3738 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3739 voe_codec.pltype = -1;
3740 if (engine()->voe()->codec()->SetRecPayloadType(
3741 channel, voe_codec) == -1) {
3742 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3743 return false;
3744 }
3745 }
3746 }
3747 return true;
3748}
3749
3750bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3751 if (playout) {
3752 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3753 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3754 LOG_RTCERR1(StartPlayout, channel);
3755 return false;
3756 }
3757 } else {
3758 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3759 engine()->voe()->base()->StopPlayout(channel);
3760 }
3761 return true;
3762}
3763
3764uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3765 bool rtcp) {
3766 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3767 uint32 ssrc = 0;
3768 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003769 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003770 }
3771 return ssrc;
3772}
3773
3774// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3775VoiceMediaChannel::Error
3776 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3777 switch (err_code) {
3778 case 0:
3779 return ERROR_NONE;
3780 case VE_CANNOT_START_RECORDING:
3781 case VE_MIC_VOL_ERROR:
3782 case VE_GET_MIC_VOL_ERROR:
3783 case VE_CANNOT_ACCESS_MIC_VOL:
3784 return ERROR_REC_DEVICE_OPEN_FAILED;
3785 case VE_SATURATION_WARNING:
3786 return ERROR_REC_DEVICE_SATURATION;
3787 case VE_REC_DEVICE_REMOVED:
3788 return ERROR_REC_DEVICE_REMOVED;
3789 case VE_RUNTIME_REC_WARNING:
3790 case VE_RUNTIME_REC_ERROR:
3791 return ERROR_REC_RUNTIME_ERROR;
3792 case VE_CANNOT_START_PLAYOUT:
3793 case VE_SPEAKER_VOL_ERROR:
3794 case VE_GET_SPEAKER_VOL_ERROR:
3795 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3796 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3797 case VE_RUNTIME_PLAY_WARNING:
3798 case VE_RUNTIME_PLAY_ERROR:
3799 return ERROR_PLAY_RUNTIME_ERROR;
3800 case VE_TYPING_NOISE_WARNING:
3801 return ERROR_REC_TYPING_NOISE_DETECTED;
3802 default:
3803 return VoiceMediaChannel::ERROR_OTHER;
3804 }
3805}
3806
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003807bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3808 int channel_id, const RtpHeaderExtension* extension) {
3809 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003810 int id = 0;
3811 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003812 if (extension) {
3813 enable = true;
3814 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003815 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003816 }
3817 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003818 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003819 return false;
3820 }
3821 return true;
3822}
3823
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003824bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3825 webrtc::ViENetwork* vie_network = NULL;
3826 int vie_channel = -1;
3827 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3828 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3829 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3830 vie_channel = shared_bwe_vie_channel_;
3831 }
3832 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3833 vie_channel) == -1) {
3834 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3835 if (vie_network != NULL) {
3836 // Don't fail if we're tearing down.
3837 return false;
3838 }
3839 }
3840 return true;
3841}
3842
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003843void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3844 DCHECK(thread_checker_.CalledOnValidThread());
3845 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3846 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3847 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3848 webrtc::AudioReceiveStream::Config config;
3849 config.rtp.remote_ssrc = ssrc;
3850 config.rtp.extensions = recv_rtp_extensions_;
3851 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3852 receive_streams_.insert(std::make_pair(ssrc, s));
3853 }
3854}
3855
3856void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3857 DCHECK(thread_checker_.CalledOnValidThread());
3858 // If we are hooked up to a webrtc::Call, assume there is an
3859 // AudioReceiveStream to destroy too.
3860 if (call_) {
3861 auto stream_it = receive_streams_.find(ssrc);
3862 if (stream_it != receive_streams_.end()) {
3863 call_->DestroyAudioReceiveStream(stream_it->second);
3864 receive_streams_.erase(stream_it);
3865 }
3866 }
3867}
3868
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003869int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003870 size_t res = 0;
3871 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003872 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003873}
3874
3875int WebRtcSoundclipStream::Rewind() {
3876 mem_.Rewind();
3877 // Return -1 to keep VoiceEngine from looping.
3878 return (loop_) ? 0 : -1;
3879}
3880
3881} // namespace cricket
3882
3883#endif // HAVE_WEBRTC_VOICE