blob: d7d71e635d6fe1f8c56d07eec378e1119b7a1b2d [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellander1afca732016-02-07 20:46:45 -08002 * Copyright (c) 2004 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellander1afca732016-02-07 20:46:45 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
henrike@webrtc.org28e20752013-07-10 00:45:36 +000011#ifdef HAVE_WEBRTC_VOICE
12
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010013#include "webrtc/media/engine/webrtcvoiceengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000014
15#include <algorithm>
16#include <cstdio>
17#include <string>
18#include <vector>
19
kjellander@webrtc.org7ffeab52016-02-26 22:46:09 +010020#include "webrtc/audio_sink.h"
tfarina5237aaf2015-11-10 23:44:30 -080021#include "webrtc/base/arraysize.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000022#include "webrtc/base/base64.h"
23#include "webrtc/base/byteorder.h"
24#include "webrtc/base/common.h"
25#include "webrtc/base/helpers.h"
26#include "webrtc/base/logging.h"
27#include "webrtc/base/stringencode.h"
28#include "webrtc/base/stringutils.h"
Peter Boströmca8b4042016-03-08 14:24:13 -080029#include "webrtc/base/trace_event.h"
ivoc112a3d82015-10-16 02:22:18 -070030#include "webrtc/call/rtc_event_log.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000031#include "webrtc/common.h"
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -080032#include "webrtc/media/base/audiosource.h"
kjellanderf4752772016-03-02 05:42:30 -080033#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080034#include "webrtc/media/base/streamparams.h"
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010035#include "webrtc/media/engine/webrtcmediaengine.h"
36#include "webrtc/media/engine/webrtcvoe.h"
solenberg26c8c912015-11-27 04:00:25 -080037#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000038#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010039#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080040#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070043namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
solenbergbd138382015-11-20 16:08:07 -080045const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
46 webrtc::kTraceWarning | webrtc::kTraceError |
47 webrtc::kTraceCritical;
48const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
49 webrtc::kTraceInfo;
50
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051// On Windows Vista and newer, Microsoft introduced the concept of "Default
52// Communications Device". This means that there are two types of default
53// devices (old Wave Audio style default and Default Communications Device).
54//
55// On Windows systems which only support Wave Audio style default, uses either
56// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070058const int kDefaultAudioDeviceId = -1;
solenberg8ad582d2016-03-16 09:34:56 -070059#elif !defined(WEBRTC_IOS)
solenbergd97ec302015-10-07 01:40:33 -070060const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061#endif
62
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063// Parameter used for NACK.
64// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070065const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000066
67// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000068// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000069
70// Recommended bitrates:
71// 8-12 kb/s for NB speech,
72// 16-20 kb/s for WB speech,
73// 28-40 kb/s for FB speech,
74// 48-64 kb/s for FB mono music, and
75// 64-128 kb/s for FB stereo music.
76// The current implementation applies the following values to mono signals,
77// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070078const int kOpusBitrateNb = 12000;
79const int kOpusBitrateWb = 20000;
80const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000081
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000082// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -070083const int kOpusMinBitrate = 6000;
84const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000085
wu@webrtc.orgde305012013-10-31 15:40:38 +000086// Default audio dscp value.
87// See http://tools.ietf.org/html/rfc2474 for details.
88// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -070089const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000090
Fredrik Solenbergb5727682015-12-04 15:22:19 +010091// Constants from voice_engine_defines.h.
92const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
93const int kMaxTelephoneEventCode = 255;
94const int kMinTelephoneEventDuration = 100;
95const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
96
solenberg31642aa2016-03-14 08:00:37 -070097const int kMinPayloadType = 0;
98const int kMaxPayloadType = 127;
99
deadbeef884f5852016-01-15 09:20:04 -0800100class ProxySink : public webrtc::AudioSinkInterface {
101 public:
102 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
103
104 void OnData(const Data& audio) override { sink_->OnData(audio); }
105
106 private:
107 webrtc::AudioSinkInterface* sink_;
108};
109
solenberg0b675462015-10-09 01:37:09 -0700110bool ValidateStreamParams(const StreamParams& sp) {
111 if (sp.ssrcs.empty()) {
112 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
113 return false;
114 }
115 if (sp.ssrcs.size() > 1) {
116 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
117 return false;
118 }
119 return true;
120}
121
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700123std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124 std::stringstream ss;
125 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
126 << " (" << codec.id << ")";
127 return ss.str();
128}
Minyue Li7100dcd2015-03-27 05:05:59 +0100129
solenbergd97ec302015-10-07 01:40:33 -0700130std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 std::stringstream ss;
132 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
133 << " (" << codec.pltype << ")";
134 return ss.str();
135}
136
solenbergd97ec302015-10-07 01:40:33 -0700137bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100138 return (_stricmp(codec.name.c_str(), ref_name) == 0);
139}
140
solenbergd97ec302015-10-07 01:40:33 -0700141bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100142 return (_stricmp(codec.plname, ref_name) == 0);
143}
144
solenbergd97ec302015-10-07 01:40:33 -0700145bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800146 const AudioCodec& codec,
147 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200148 for (const AudioCodec& c : codecs) {
149 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200151 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152 }
153 return true;
154 }
155 }
156 return false;
157}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000158
solenberg0b675462015-10-09 01:37:09 -0700159bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
160 if (codecs.empty()) {
161 return true;
162 }
163 std::vector<int> payload_types;
164 for (const AudioCodec& codec : codecs) {
165 payload_types.push_back(codec.id);
166 }
167 std::sort(payload_types.begin(), payload_types.end());
168 auto it = std::unique(payload_types.begin(), payload_types.end());
169 return it == payload_types.end();
170}
171
Minyue Li7100dcd2015-03-27 05:05:59 +0100172// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800173bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100174 int value;
175 return codec.GetParam(feature, &value) && value == 1;
176}
177
178// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
179// otherwise. If the value (either from params or codec.bitrate) <=0, use the
180// default configuration. If the value is beyond feasible bit rate of Opus,
181// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700182int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100183 int bitrate = 0;
184 bool use_param = true;
185 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
186 bitrate = codec.bitrate;
187 use_param = false;
188 }
189 if (bitrate <= 0) {
190 if (max_playback_rate <= 8000) {
191 bitrate = kOpusBitrateNb;
192 } else if (max_playback_rate <= 16000) {
193 bitrate = kOpusBitrateWb;
194 } else {
195 bitrate = kOpusBitrateFb;
196 }
197
198 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
199 bitrate *= 2;
200 }
201 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
202 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
203 std::string rate_source =
204 use_param ? "Codec parameter \"maxaveragebitrate\"" :
205 "Supplied Opus bitrate";
206 LOG(LS_WARNING) << rate_source
207 << " is invalid and is replaced by: "
208 << bitrate;
209 }
210 return bitrate;
211}
212
213// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
214// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700215int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100216 int value;
217 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
218 return value;
219 }
220 return kOpusDefaultMaxPlaybackRate;
221}
222
solenbergd97ec302015-10-07 01:40:33 -0700223void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100224 bool* enable_codec_fec, int* max_playback_rate,
225 bool* enable_codec_dtx) {
226 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
227 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
228 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
229
230 // If OPUS, change what we send according to the "stereo" codec
231 // parameter, and not the "channels" parameter. We set
232 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
233 // the bitrate is not specified, i.e. is <= zero, we set it to the
234 // appropriate default value for mono or stereo Opus.
235
236 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
237 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
238}
239
solenberg566ef242015-11-06 15:34:49 -0800240webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
241 webrtc::AudioState::Config config;
242 config.voice_engine = voe_wrapper->engine();
243 return config;
244}
245
solenberg26c8c912015-11-27 04:00:25 -0800246class WebRtcVoiceCodecs final {
247 public:
248 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
249 // list and add a test which verifies VoE supports the listed codecs.
250 static std::vector<AudioCodec> SupportedCodecs() {
solenberg26c8c912015-11-27 04:00:25 -0800251 std::vector<AudioCodec> result;
deadbeef67cf2c12016-04-13 10:07:16 -0700252 // Iterate first over our preferred codecs list, so that the results are
253 // added in order of preference.
254 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
255 const CodecPref* pref = &kCodecPrefs[i];
256 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
257 // Change the sample rate of G722 to 8000 to match SDP.
258 MaybeFixupG722(&voe_codec, 8000);
259 // Skip uncompressed formats.
260 if (IsCodec(voe_codec, kL16CodecName)) {
261 continue;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000262 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000263
deadbeef67cf2c12016-04-13 10:07:16 -0700264 if (!IsCodec(voe_codec, pref->name) ||
265 pref->clockrate != voe_codec.plfreq ||
266 pref->channels != voe_codec.channels) {
267 // Not a match.
268 continue;
269 }
270
271 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
272 voe_codec.rate, voe_codec.channels);
273 LOG(LS_INFO) << "Adding supported codec: " << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100274 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000275 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000276 codec.bitrate = 0;
277 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100278 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000279 // Only add fmtp parameters that differ from the spec.
280 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
281 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000282 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000283 }
284 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
285 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000286 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000287 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000288 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800289 codec.AddFeedbackParam(
290 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000291
292 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000293 // when they can be set to values other than the default.
294 }
solenberg26c8c912015-11-27 04:00:25 -0800295 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000296 }
297 }
solenberg26c8c912015-11-27 04:00:25 -0800298 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000299 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000300
solenberg26c8c912015-11-27 04:00:25 -0800301 static bool ToCodecInst(const AudioCodec& in,
302 webrtc::CodecInst* out) {
303 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
304 // Change the sample rate of G722 to 8000 to match SDP.
305 MaybeFixupG722(&voe_codec, 8000);
306 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
deadbeef67cf2c12016-04-13 10:07:16 -0700307 voe_codec.rate, voe_codec.channels);
solenberg26c8c912015-11-27 04:00:25 -0800308 bool multi_rate = IsCodecMultiRate(voe_codec);
309 // Allow arbitrary rates for ISAC to be specified.
310 if (multi_rate) {
311 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
312 codec.bitrate = 0;
313 }
314 if (codec.Matches(in)) {
315 if (out) {
316 // Fixup the payload type.
317 voe_codec.pltype = in.id;
318
319 // Set bitrate if specified.
320 if (multi_rate && in.bitrate != 0) {
321 voe_codec.rate = in.bitrate;
322 }
323
324 // Reset G722 sample rate to 16000 to match WebRTC.
325 MaybeFixupG722(&voe_codec, 16000);
326
327 // Apply codec-specific settings.
328 if (IsCodec(codec, kIsacCodecName)) {
329 // If ISAC and an explicit bitrate is not specified,
330 // enable auto bitrate adjustment.
331 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
332 }
333 *out = voe_codec;
334 }
335 return true;
336 }
337 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000338 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000339 }
solenberg26c8c912015-11-27 04:00:25 -0800340
341 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
342 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
343 if (IsCodec(codec, kCodecPrefs[i].name) &&
344 kCodecPrefs[i].clockrate == codec.plfreq) {
345 return kCodecPrefs[i].is_multi_rate;
346 }
347 }
348 return false;
349 }
350
351 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
352 // codec pacsize if it's valid, or we will pick the next smallest value we
353 // support.
354 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
355 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
356 for (const CodecPref& codec_pref : kCodecPrefs) {
357 if ((IsCodec(*codec, codec_pref.name) &&
358 codec_pref.clockrate == codec->plfreq) ||
359 IsCodec(*codec, kG722CodecName)) {
360 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
361 if (packet_size_ms) {
362 // Convert unit from milli-seconds to samples.
363 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
364 return true;
365 }
366 }
367 }
368 return false;
369 }
370
stefanba4c0e42016-02-04 04:12:24 -0800371 static const AudioCodec* GetPreferredCodec(
372 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800373 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800374 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800375 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800376 RTC_DCHECK(red_payload_type);
377 // Select the preferred send codec (the first non-telephone-event/CN codec).
378 for (const AudioCodec& codec : codecs) {
379 *red_payload_type = -1;
380 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
381 // Skip telephone-event/CN codec, which will be handled later.
382 continue;
383 }
384
385 // We'll use the first codec in the list to actually send audio data.
386 // Be sure to use the payload type requested by the remote side.
387 // "red", for RED audio, is a special case where the actual codec to be
388 // used is specified in params.
389 const AudioCodec* found_codec = &codec;
390 if (IsCodec(*found_codec, kRedCodecName)) {
391 // Parse out the RED parameters. If we fail, just ignore RED;
392 // we don't support all possible params/usage scenarios.
393 *red_payload_type = codec.id;
394 found_codec = GetRedSendCodec(*found_codec, codecs);
395 if (!found_codec) {
396 continue;
397 }
398 }
399 // Ignore codecs we don't know about. The negotiation step should prevent
400 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800401 webrtc::CodecInst voe_codec = {0};
402 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800403 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
404 continue;
405 }
solenberg72e29d22016-03-08 06:35:16 -0800406 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800407 return found_codec;
408 }
409 return nullptr;
410 }
411
solenberg26c8c912015-11-27 04:00:25 -0800412 private:
413 static const int kMaxNumPacketSize = 6;
414 struct CodecPref {
415 const char* name;
416 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800417 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800418 int payload_type;
419 bool is_multi_rate;
420 int packet_sizes_ms[kMaxNumPacketSize];
421 };
422 // Note: keep the supported packet sizes in ascending order.
423 static const CodecPref kCodecPrefs[12];
424
425 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
426 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
427 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
428 if (packet_size_ms && packet_size_ms <= ptime_ms) {
429 selected_packet_size_ms = packet_size_ms;
430 }
431 }
432 return selected_packet_size_ms;
433 }
434
435 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
436 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
437 // codec.
438 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
439 if (IsCodec(*voe_codec, kG722CodecName)) {
440 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
441 // has changed, and this special case is no longer needed.
442 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
443 voe_codec->plfreq = new_plfreq;
444 }
445 }
stefanba4c0e42016-02-04 04:12:24 -0800446
447 static const AudioCodec* GetRedSendCodec(
448 const AudioCodec& red_codec,
449 const std::vector<AudioCodec>& all_codecs) {
450 // Get the RED encodings from the parameter with no name. This may
451 // change based on what is discussed on the Jingle list.
452 // The encoding parameter is of the form "a/b"; we only support where
453 // a == b. Verify this and parse out the value into red_pt.
454 // If the parameter value is absent (as it will be until we wire up the
455 // signaling of this message), use the second codec specified (i.e. the
456 // one after "red") as the encoding parameter.
457 int red_pt = -1;
458 std::string red_params;
459 CodecParameterMap::const_iterator it = red_codec.params.find("");
460 if (it != red_codec.params.end()) {
461 red_params = it->second;
462 std::vector<std::string> red_pts;
463 if (rtc::split(red_params, '/', &red_pts) != 2 ||
464 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
465 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
466 return nullptr;
467 }
468 } else if (red_codec.params.empty()) {
469 LOG(LS_WARNING) << "RED params not present, using defaults";
470 if (all_codecs.size() > 1) {
471 red_pt = all_codecs[1].id;
472 }
473 }
474
475 // Try to find red_pt in |codecs|.
476 for (const AudioCodec& codec : all_codecs) {
477 if (codec.id == red_pt) {
478 return &codec;
479 }
480 }
481 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
482 return nullptr;
483 }
solenberg26c8c912015-11-27 04:00:25 -0800484};
485
486const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
487 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
488 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
489 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
490 // G722 should be advertised as 8000 Hz because of the RFC "bug".
491 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
492 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
493 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
494 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
495 { kCnCodecName, 32000, 1, 106, false, { } },
496 { kCnCodecName, 16000, 1, 105, false, { } },
497 { kCnCodecName, 8000, 1, 13, false, { } },
498 { kRedCodecName, 8000, 1, 127, false, { } },
499 { kDtmfCodecName, 8000, 1, 126, false, { } },
500};
501} // namespace {
502
503bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
504 webrtc::CodecInst* out) {
505 return WebRtcVoiceCodecs::ToCodecInst(in, out);
506}
507
solenbergff976312016-03-30 23:28:51 -0700508WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm)
509 : WebRtcVoiceEngine(adm, new VoEWrapper()) {
510 audio_state_ = webrtc::AudioState::Create(MakeAudioStateConfig(voe()));
solenberg26c8c912015-11-27 04:00:25 -0800511}
512
solenbergff976312016-03-30 23:28:51 -0700513WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm,
514 VoEWrapper* voe_wrapper)
515 : adm_(adm), voe_wrapper_(voe_wrapper) {
solenberg26c8c912015-11-27 04:00:25 -0800516 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700517 LOG(LS_INFO) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
518 RTC_DCHECK(voe_wrapper);
solenberg26c8c912015-11-27 04:00:25 -0800519
520 signal_thread_checker_.DetachFromThread();
solenberg26c8c912015-11-27 04:00:25 -0800521
522 // Load our audio codec list.
solenbergff976312016-03-30 23:28:51 -0700523 LOG(LS_INFO) << "Supported codecs in order of preference:";
solenberg26c8c912015-11-27 04:00:25 -0800524 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
solenbergff976312016-03-30 23:28:51 -0700525 for (const AudioCodec& codec : codecs_) {
526 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000527 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528
solenbergff976312016-03-30 23:28:51 -0700529 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000530
solenbergff976312016-03-30 23:28:51 -0700531 // Temporarily turn logging level up for the Init() call.
532 webrtc::Trace::SetTraceCallback(this);
solenbergbd138382015-11-20 16:08:07 -0800533 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800534 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
solenbergff976312016-03-30 23:28:51 -0700535 RTC_CHECK_EQ(0, voe_wrapper_->base()->Init(adm_.get()));
solenbergbd138382015-11-20 16:08:07 -0800536 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537
solenbergff976312016-03-30 23:28:51 -0700538 // No ADM supplied? Get the default one from VoE.
539 if (!adm_) {
540 adm_ = voe_wrapper_->base()->audio_device_module();
541 }
542 RTC_DCHECK(adm_);
543
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000544 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800545 // calling ApplyOptions or the default will be overwritten.
solenbergff976312016-03-30 23:28:51 -0700546 int error = voe_wrapper_->processing()->GetAgcConfig(default_agc_config_);
547 RTC_DCHECK_EQ(0, error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000548
solenberg0f7d2932016-01-15 01:40:39 -0800549 // Set default engine options.
550 {
551 AudioOptions options;
552 options.echo_cancellation = rtc::Optional<bool>(true);
553 options.auto_gain_control = rtc::Optional<bool>(true);
554 options.noise_suppression = rtc::Optional<bool>(true);
555 options.highpass_filter = rtc::Optional<bool>(true);
556 options.stereo_swapping = rtc::Optional<bool>(false);
557 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
558 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
559 options.typing_detection = rtc::Optional<bool>(true);
560 options.adjust_agc_delta = rtc::Optional<int>(0);
561 options.experimental_agc = rtc::Optional<bool>(false);
562 options.extended_filter_aec = rtc::Optional<bool>(false);
563 options.delay_agnostic_aec = rtc::Optional<bool>(false);
564 options.experimental_ns = rtc::Optional<bool>(false);
solenbergff976312016-03-30 23:28:51 -0700565 bool error = ApplyOptions(options);
566 RTC_DCHECK(error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567 }
568
solenberg246b8172015-12-08 09:50:23 -0800569 SetDefaultDevices();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000570}
571
solenbergff976312016-03-30 23:28:51 -0700572WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800573 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700574 LOG(LS_INFO) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000575 StopAecDump();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 voe_wrapper_->base()->Terminate();
solenbergff976312016-03-30 23:28:51 -0700577 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000578}
579
solenberg566ef242015-11-06 15:34:49 -0800580rtc::scoped_refptr<webrtc::AudioState>
581 WebRtcVoiceEngine::GetAudioState() const {
582 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
583 return audio_state_;
584}
585
nisse51542be2016-02-12 02:27:06 -0800586VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
587 webrtc::Call* call,
588 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200589 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800590 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800591 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000592}
593
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000594bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800595 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700596 LOG(LS_INFO) << "WebRtcVoiceEngine::ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800597 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800598
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000599 // kEcConference is AEC with high suppression.
600 webrtc::EcModes ec_mode = webrtc::kEcConference;
601 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
602 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
603 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700604 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000605 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700606 << *options.aecm_generate_comfort_noise
607 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000608 }
609
kjellanderfcfc8042016-01-14 11:01:09 -0800610#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000611 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100612 options.echo_cancellation = rtc::Optional<bool>(false);
613 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200614 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000615#elif defined(ANDROID)
616 ec_mode = webrtc::kEcAecm;
617#endif
618
kjellanderfcfc8042016-01-14 11:01:09 -0800619#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000620 // Set the AGC mode for iOS as well despite disabling it above, to avoid
621 // unsupported configuration errors from webrtc.
622 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100623 options.typing_detection = rtc::Optional<bool>(false);
624 options.experimental_agc = rtc::Optional<bool>(false);
625 options.extended_filter_aec = rtc::Optional<bool>(false);
626 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000627#endif
628
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100629 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
630 // where the feature is not supported.
631 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800632#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700633 if (options.delay_agnostic_aec) {
634 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100635 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100636 options.echo_cancellation = rtc::Optional<bool>(true);
637 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100638 ec_mode = webrtc::kEcConference;
639 }
640 }
641#endif
642
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000643 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
644
kwiberg102c6a62015-10-30 02:47:38 -0700645 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000646 // Check if platform supports built-in EC. Currently only supported on
647 // Android and in combination with Java based audio layer.
648 // TODO(henrika): investigate possibility to support built-in EC also
649 // in combination with Open SL ES audio.
solenberg5b5129a2016-04-08 05:35:48 -0700650 const bool built_in_aec = adm()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200651 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200652 // Built-in EC exists on this device and use_delay_agnostic_aec is not
653 // overriding it. Enable/Disable it according to the echo_cancellation
654 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200655 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700656 *options.echo_cancellation && !use_delay_agnostic_aec;
solenberg5b5129a2016-04-08 05:35:48 -0700657 if (adm()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
Bjorn Volcker73f72102015-06-03 14:50:15 +0200658 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100659 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000660 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100661 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000662 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
663 }
664 }
kwiberg102c6a62015-10-30 02:47:38 -0700665 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
666 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000667 return false;
668 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700669 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200670 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000671 }
672#if !defined(ANDROID)
673 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700674 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
675 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000676 return false;
677 }
678#endif
679 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700680 bool cn = options.aecm_generate_comfort_noise.value_or(false);
681 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
682 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000683 return false;
684 }
685 }
686 }
687
kwiberg102c6a62015-10-30 02:47:38 -0700688 if (options.auto_gain_control) {
solenberg5b5129a2016-04-08 05:35:48 -0700689 const bool built_in_agc = adm()->BuiltInAGCIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200690 if (built_in_agc) {
solenberg5b5129a2016-04-08 05:35:48 -0700691 if (adm()->EnableBuiltInAGC(*options.auto_gain_control) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700692 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200693 // Disable internal software AGC if built-in AGC is enabled,
694 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100695 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200696 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
697 }
698 }
kwiberg102c6a62015-10-30 02:47:38 -0700699 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
700 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000701 return false;
702 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700703 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
704 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000705 }
706 }
707
kwiberg102c6a62015-10-30 02:47:38 -0700708 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
709 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000710 // Override default_agc_config_. Generally, an unset option means "leave
711 // the VoE bits alone" in this function, so we want whatever is set to be
712 // stored as the new "default". If we didn't, then setting e.g.
713 // tx_agc_target_dbov would reset digital compression gain and limiter
714 // settings.
715 // Also, if we don't update default_agc_config_, then adjust_agc_delta
716 // would be an offset from the original values, and not whatever was set
717 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700718 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
719 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000720 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700721 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000722 default_agc_config_.digitalCompressionGaindB);
723 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700724 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000725 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
726 LOG_RTCERR3(SetAgcConfig,
727 default_agc_config_.targetLeveldBOv,
728 default_agc_config_.digitalCompressionGaindB,
729 default_agc_config_.limiterEnable);
730 return false;
731 }
732 }
733
kwiberg102c6a62015-10-30 02:47:38 -0700734 if (options.noise_suppression) {
solenberg5b5129a2016-04-08 05:35:48 -0700735 const bool built_in_ns = adm()->BuiltInNSIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200736 if (built_in_ns) {
solenberg5b5129a2016-04-08 05:35:48 -0700737 if (adm()->EnableBuiltInNS(*options.noise_suppression) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700738 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200739 // Disable internal software NS if built-in NS is enabled,
740 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100741 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200742 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
743 }
744 }
kwiberg102c6a62015-10-30 02:47:38 -0700745 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
746 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000747 return false;
748 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700749 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200750 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000751 }
752 }
753
kwiberg102c6a62015-10-30 02:47:38 -0700754 if (options.highpass_filter) {
755 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
756 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
757 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000758 return false;
759 }
760 }
761
kwiberg102c6a62015-10-30 02:47:38 -0700762 if (options.stereo_swapping) {
763 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
764 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
765 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
766 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000767 return false;
768 }
769 }
770
kwiberg102c6a62015-10-30 02:47:38 -0700771 if (options.audio_jitter_buffer_max_packets) {
772 LOG(LS_INFO) << "NetEq capacity is "
773 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200774 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700775 new webrtc::NetEqCapacityConfig(
776 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200777 }
778
kwiberg102c6a62015-10-30 02:47:38 -0700779 if (options.audio_jitter_buffer_fast_accelerate) {
780 LOG(LS_INFO) << "NetEq fast mode? "
781 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200782 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700783 new webrtc::NetEqFastAccelerate(
784 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200785 }
786
kwiberg102c6a62015-10-30 02:47:38 -0700787 if (options.typing_detection) {
788 LOG(LS_INFO) << "Typing detection is enabled? "
789 << *options.typing_detection;
790 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000791 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700792 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000793 }
794 }
795
kwiberg102c6a62015-10-30 02:47:38 -0700796 if (options.adjust_agc_delta) {
797 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
798 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000799 return false;
800 }
801 }
802
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000803 webrtc::Config config;
804
kwiberg102c6a62015-10-30 02:47:38 -0700805 if (options.delay_agnostic_aec)
806 delay_agnostic_aec_ = options.delay_agnostic_aec;
807 if (delay_agnostic_aec_) {
808 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700809 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700810 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100811 }
812
kwiberg102c6a62015-10-30 02:47:38 -0700813 if (options.extended_filter_aec) {
814 extended_filter_aec_ = options.extended_filter_aec;
815 }
816 if (extended_filter_aec_) {
817 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200818 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700819 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000820 }
821
kwiberg102c6a62015-10-30 02:47:38 -0700822 if (options.experimental_ns) {
823 experimental_ns_ = options.experimental_ns;
824 }
825 if (experimental_ns_) {
826 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000827 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700828 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000829 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000830
831 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
832 // returns NULL on audio_processing().
833 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
834 if (audioproc) {
835 audioproc->SetExtraOptions(config);
836 }
837
kwiberg102c6a62015-10-30 02:47:38 -0700838 if (options.recording_sample_rate) {
839 LOG(LS_INFO) << "Recording sample rate is "
840 << *options.recording_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700841 if (adm()->SetRecordingSampleRate(*options.recording_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700842 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000843 }
844 }
845
kwiberg102c6a62015-10-30 02:47:38 -0700846 if (options.playout_sample_rate) {
847 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700848 if (adm()->SetPlayoutSampleRate(*options.playout_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700849 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000850 }
851 }
852
853 return true;
854}
855
solenberg246b8172015-12-08 09:50:23 -0800856void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800857 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800858#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800859 int in_id = kDefaultAudioDeviceId;
860 int out_id = kDefaultAudioDeviceId;
861 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
862 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000863
solenbergc1a1b352015-09-22 13:31:20 -0700864 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800865 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
866 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000867 ret = false;
868 }
solenberg246b8172015-12-08 09:50:23 -0800869 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
870 if (ap) {
871 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 }
873
solenberg246b8172015-12-08 09:50:23 -0800874 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
875 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 ret = false;
877 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800880 LOG(LS_INFO) << "Set microphone to (id=" << in_id
881 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882 }
kjellanderfcfc8042016-01-14 11:01:09 -0800883#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800887 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 unsigned int ulevel;
889 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
890 LOG_RTCERR1(GetSpeakerVolume, level);
891 return false;
892 }
893 *level = ulevel;
894 return true;
895}
896
897bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800898 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700899 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
901 LOG_RTCERR1(SetSpeakerVolume, level);
902 return false;
903 }
904 return true;
905}
906
907int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800908 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909 unsigned int ulevel;
910 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
911 static_cast<int>(ulevel) : -1;
912}
913
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800915 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916 return codecs_;
917}
918
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100919RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800920 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100921 RtpCapabilities capabilities;
922 capabilities.header_extensions.push_back(RtpHeaderExtension(
923 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
924 capabilities.header_extensions.push_back(
925 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
926 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800927 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
928 "Enabled") {
929 capabilities.header_extensions.push_back(RtpHeaderExtension(
930 kRtpTransportSequenceNumberHeaderExtension,
931 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
932 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100933 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800937 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 return voe_wrapper_->error();
939}
940
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
942 int length) {
solenberg566ef242015-11-06 15:34:49 -0800943 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000946 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000950 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000952 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
solenberg72e29d22016-03-08 06:35:16 -0800954 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (length < 72) {
956 std::string msg(trace, length);
957 LOG(LS_ERROR) << "Malformed webrtc log message: ";
958 LOG_V(sev) << msg;
959 } else {
960 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +0200961 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 }
963}
964
solenberg63b34542015-09-29 06:06:31 -0700965void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800966 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
967 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 channels_.push_back(channel);
969}
970
solenberg63b34542015-09-29 06:06:31 -0700971void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800972 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -0700973 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -0800974 RTC_DCHECK(it != channels_.end());
975 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976}
977
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978// Adjusts the default AGC target level by the specified delta.
979// NB: If we start messing with other config fields, we'll want
980// to save the current webrtc::AgcConfig as well.
981bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -0800982 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 webrtc::AgcConfig config = default_agc_config_;
984 config.targetLeveldBOv -= delta;
985
986 LOG(LS_INFO) << "Adjusting AGC level from default -"
987 << default_agc_config_.targetLeveldBOv << "dB to -"
988 << config.targetLeveldBOv << "dB";
989
990 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
991 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
992 return false;
993 }
994 return true;
995}
996
ivocd66b44d2016-01-15 03:06:36 -0800997bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
998 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -0800999 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001000 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001001 if (!aec_dump_file_stream) {
1002 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001003 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001004 LOG(LS_WARNING) << "Could not close file.";
1005 return false;
1006 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001007 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001008 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1009 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001010 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001011 LOG_RTCERR0(StartDebugRecording);
1012 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001013 return false;
1014 }
1015 is_dumping_aec_ = true;
1016 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001017}
1018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001020 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 if (!is_dumping_aec_) {
1022 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001023 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1024 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001025 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 } else {
1027 is_dumping_aec_ = true;
1028 }
1029 }
1030}
1031
1032void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001033 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 if (is_dumping_aec_) {
1035 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001036 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 webrtc::AudioProcessing::kNoError) {
1038 LOG_RTCERR0(StopDebugRecording);
1039 }
1040 is_dumping_aec_ = false;
1041 }
1042}
1043
ivoc112a3d82015-10-16 02:22:18 -07001044bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001045 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001046 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1047 if (event_log) {
1048 return event_log->StartLogging(file);
1049 }
1050 LOG_RTCERR0(StartRtcEventLog);
1051 return false;
ivoc112a3d82015-10-16 02:22:18 -07001052}
1053
1054void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001055 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001056 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1057 if (event_log) {
1058 event_log->StopLogging();
1059 return;
1060 }
1061 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001062}
1063
solenberg0a617e22015-10-20 15:49:38 -07001064int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001065 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001066 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001067}
1068
solenberg5b5129a2016-04-08 05:35:48 -07001069webrtc::AudioDeviceModule* WebRtcVoiceEngine::adm() {
1070 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1071 RTC_DCHECK(adm_);
1072 return adm_;
1073}
1074
solenbergc96df772015-10-21 13:01:53 -07001075class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001076 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001077 public:
skvlade0d46372016-04-07 22:59:22 -07001078 WebRtcAudioSendStream(int ch,
1079 webrtc::AudioTransport* voe_audio_transport,
1080 uint32_t ssrc,
1081 const std::string& c_name,
solenberg3a941542015-11-16 07:34:50 -08001082 const std::vector<webrtc::RtpExtension>& extensions,
1083 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001084 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001085 call_(call),
skvlade0d46372016-04-07 22:59:22 -07001086 config_(nullptr),
1087 rtp_parameters_(CreateRtpParametersWithOneEncoding()) {
solenberg85a04962015-10-27 03:35:21 -07001088 RTC_DCHECK_GE(ch, 0);
1089 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1090 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001091 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001092 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001093 config_.rtp.ssrc = ssrc;
1094 config_.rtp.c_name = c_name;
1095 config_.voe_channel_id = ch;
1096 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001097 }
solenberg3a941542015-11-16 07:34:50 -08001098
solenbergc96df772015-10-21 13:01:53 -07001099 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001100 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001101 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001102 call_->DestroyAudioSendStream(stream_);
1103 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001104
solenberg3a941542015-11-16 07:34:50 -08001105 void RecreateAudioSendStream(
1106 const std::vector<webrtc::RtpExtension>& extensions) {
1107 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1108 if (stream_) {
1109 call_->DestroyAudioSendStream(stream_);
1110 stream_ = nullptr;
1111 }
1112 config_.rtp.extensions = extensions;
1113 RTC_DCHECK(!stream_);
1114 stream_ = call_->CreateAudioSendStream(config_);
1115 RTC_CHECK(stream_);
solenberg6d6e7c52016-04-13 09:07:30 -07001116 UpdateSendState();
solenberg3a941542015-11-16 07:34:50 -08001117 }
1118
solenberg8842c3e2016-03-11 03:06:41 -08001119 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001120 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1121 RTC_DCHECK(stream_);
1122 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1123 }
1124
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001125 void SetSend(bool send) {
1126 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1127 send_ = send;
1128 UpdateSendState();
1129 }
1130
solenberg3a941542015-11-16 07:34:50 -08001131 webrtc::AudioSendStream::Stats GetStats() const {
1132 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1133 RTC_DCHECK(stream_);
1134 return stream_->GetStats();
1135 }
1136
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001137 // Starts the sending by setting ourselves as a sink to the AudioSource to
1138 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001139 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001140 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001141 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001142 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001143 RTC_DCHECK(source);
1144 if (source_) {
1145 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001146 return;
1147 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001148 source->SetSink(this);
1149 source_ = source;
1150 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001151 }
1152
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001153 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001154 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001155 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001156 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001157 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001158 if (source_) {
1159 source_->SetSink(nullptr);
1160 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001161 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001162 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001163 }
1164
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001165 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001166 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001167 void OnData(const void* audio_data,
1168 int bits_per_sample,
1169 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001170 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001171 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001172 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001173 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001174 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001175 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001176 audio_data,
1177 bits_per_sample,
1178 sample_rate,
1179 number_of_channels,
1180 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001181 }
1182
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001183 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001184 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001185 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001186 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001187 // Set |source_| to nullptr to make sure no more callback will get into
1188 // the source.
1189 source_ = nullptr;
1190 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001191 }
1192
1193 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001194 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001195 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001196 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001197 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001198
skvlade0d46372016-04-07 22:59:22 -07001199 const webrtc::RtpParameters& rtp_parameters() const {
1200 return rtp_parameters_;
1201 }
1202
1203 void set_rtp_parameters(const webrtc::RtpParameters& parameters) {
1204 RTC_CHECK_EQ(1UL, parameters.encodings.size());
1205 rtp_parameters_ = parameters;
1206 }
1207
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001208 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001209 void UpdateSendState() {
1210 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1211 RTC_DCHECK(stream_);
1212 if (send_ && source_ != nullptr) {
1213 stream_->Start();
1214 } else { // !send || source_ = nullptr
1215 stream_->Stop();
1216 }
1217 }
1218
solenberg566ef242015-11-06 15:34:49 -08001219 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001220 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001221 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1222 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001223 webrtc::AudioSendStream::Config config_;
1224 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1225 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001226 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001227
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001228 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001229 // PeerConnection will make sure invalidating the pointer before the object
1230 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001231 AudioSource* source_ = nullptr;
1232 bool send_ = false;
skvlade0d46372016-04-07 22:59:22 -07001233 webrtc::RtpParameters rtp_parameters_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001234
solenbergc96df772015-10-21 13:01:53 -07001235 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1236};
1237
1238class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1239 public:
stefanba4c0e42016-02-04 04:12:24 -08001240 WebRtcAudioReceiveStream(int ch,
1241 uint32_t remote_ssrc,
1242 uint32_t local_ssrc,
1243 bool use_transport_cc,
1244 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001245 const std::vector<webrtc::RtpExtension>& extensions,
1246 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001247 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001248 RTC_DCHECK_GE(ch, 0);
1249 RTC_DCHECK(call);
1250 config_.rtp.remote_ssrc = remote_ssrc;
1251 config_.rtp.local_ssrc = local_ssrc;
1252 config_.voe_channel_id = ch;
1253 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001254 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001255 }
solenbergc96df772015-10-21 13:01:53 -07001256
solenberg7add0582015-11-20 09:59:34 -08001257 ~WebRtcAudioReceiveStream() {
1258 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1259 call_->DestroyAudioReceiveStream(stream_);
1260 }
1261
1262 void RecreateAudioReceiveStream(
1263 const std::vector<webrtc::RtpExtension>& extensions) {
1264 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001265 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001266 }
stefanba4c0e42016-02-04 04:12:24 -08001267 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001268 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001269 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001270 }
1271
1272 webrtc::AudioReceiveStream::Stats GetStats() const {
1273 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1274 RTC_DCHECK(stream_);
1275 return stream_->GetStats();
1276 }
1277
1278 int channel() const {
1279 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1280 return config_.voe_channel_id;
1281 }
solenbergc96df772015-10-21 13:01:53 -07001282
kwiberg686a8ef2016-02-26 03:00:35 -08001283 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001284 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001285 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001286 }
1287
solenbergc96df772015-10-21 13:01:53 -07001288 private:
stefanba4c0e42016-02-04 04:12:24 -08001289 void RecreateAudioReceiveStream(
1290 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001291 const std::vector<webrtc::RtpExtension>& extensions) {
1292 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1293 if (stream_) {
1294 call_->DestroyAudioReceiveStream(stream_);
1295 stream_ = nullptr;
1296 }
1297 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001298 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001299 RTC_DCHECK(!stream_);
1300 stream_ = call_->CreateAudioReceiveStream(config_);
1301 RTC_CHECK(stream_);
1302 }
1303
1304 rtc::ThreadChecker worker_thread_checker_;
1305 webrtc::Call* call_ = nullptr;
1306 webrtc::AudioReceiveStream::Config config_;
1307 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1308 // configuration changes.
1309 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001310
1311 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001312};
1313
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001314WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001315 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001316 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001317 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001318 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001319 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001320 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001321 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001322 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323}
1324
1325WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001326 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001327 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001328 // TODO(solenberg): Should be able to delete the streams directly, without
1329 // going through RemoveNnStream(), once stream objects handle
1330 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001331 while (!send_streams_.empty()) {
1332 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001333 }
solenberg7add0582015-11-20 09:59:34 -08001334 while (!recv_streams_.empty()) {
1335 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336 }
solenberg0a617e22015-10-20 15:49:38 -07001337 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338}
1339
nisse51542be2016-02-12 02:27:06 -08001340rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1341 return kAudioDscpValue;
1342}
1343
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001344bool WebRtcVoiceMediaChannel::SetSendParameters(
1345 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001346 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001347 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001348 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1349 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001350 // TODO(pthatcher): Refactor this to be more clean now that we have
1351 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001352
1353 if (!SetSendCodecs(params.codecs)) {
1354 return false;
1355 }
1356
solenberg7e4e01a2015-12-02 08:05:01 -08001357 if (!ValidateRtpExtensions(params.extensions)) {
1358 return false;
1359 }
1360 std::vector<webrtc::RtpExtension> filtered_extensions =
1361 FilterRtpExtensions(params.extensions,
1362 webrtc::RtpExtension::IsSupportedForAudio, true);
1363 if (send_rtp_extensions_ != filtered_extensions) {
1364 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001365 for (auto& it : send_streams_) {
1366 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1367 }
1368 }
1369
skvlade0d46372016-04-07 22:59:22 -07001370 if (!SetSendBitrate(params.max_bandwidth_bps)) {
solenberg3a941542015-11-16 07:34:50 -08001371 return false;
1372 }
1373 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001374}
1375
1376bool WebRtcVoiceMediaChannel::SetRecvParameters(
1377 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001378 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001379 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001380 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1381 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001382 // TODO(pthatcher): Refactor this to be more clean now that we have
1383 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001384
1385 if (!SetRecvCodecs(params.codecs)) {
1386 return false;
1387 }
1388
solenberg7e4e01a2015-12-02 08:05:01 -08001389 if (!ValidateRtpExtensions(params.extensions)) {
1390 return false;
1391 }
1392 std::vector<webrtc::RtpExtension> filtered_extensions =
1393 FilterRtpExtensions(params.extensions,
1394 webrtc::RtpExtension::IsSupportedForAudio, false);
1395 if (recv_rtp_extensions_ != filtered_extensions) {
1396 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001397 for (auto& it : recv_streams_) {
1398 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1399 }
1400 }
solenberg7add0582015-11-20 09:59:34 -08001401 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001402}
1403
skvlade0d46372016-04-07 22:59:22 -07001404webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpParameters(
1405 uint32_t ssrc) const {
1406 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1407 auto it = send_streams_.find(ssrc);
1408 if (it == send_streams_.end()) {
1409 LOG(LS_WARNING) << "Attempting to get RTP parameters for stream with ssrc "
1410 << ssrc << " which doesn't exist.";
1411 return webrtc::RtpParameters();
1412 }
1413
1414 return it->second->rtp_parameters();
1415}
1416
1417bool WebRtcVoiceMediaChannel::SetRtpParameters(
1418 uint32_t ssrc,
1419 const webrtc::RtpParameters& parameters) {
1420 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1421 if (!ValidateRtpParameters(parameters)) {
1422 return false;
1423 }
1424 auto it = send_streams_.find(ssrc);
1425 if (it == send_streams_.end()) {
1426 LOG(LS_WARNING) << "Attempting to set RTP parameters for stream with ssrc "
1427 << ssrc << " which doesn't exist.";
1428 return false;
1429 }
1430
1431 if (!SetChannelParameters(it->second->channel(), parameters)) {
1432 LOG(LS_WARNING) << "Failed to set RtpParameters.";
1433 return false;
1434 }
1435 it->second->set_rtp_parameters(parameters);
1436 return true;
1437}
1438
1439bool WebRtcVoiceMediaChannel::ValidateRtpParameters(
1440 const webrtc::RtpParameters& rtp_parameters) {
1441 if (rtp_parameters.encodings.size() != 1) {
1442 LOG(LS_ERROR)
1443 << "Attempted to set RtpParameters without exactly one encoding";
1444 return false;
1445 }
1446 return true;
1447}
1448
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001450 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 LOG(LS_INFO) << "Setting voice channel options: "
1452 << options.ToString();
1453
1454 // We retain all of the existing options, and apply the given ones
1455 // on top. This means there is no way to "clear" options such that
1456 // they go back to the engine default.
1457 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001458 if (!engine()->ApplyOptions(options_)) {
1459 LOG(LS_WARNING) <<
1460 "Failed to apply engine options during channel SetOptions.";
1461 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 LOG(LS_INFO) << "Set voice channel options. Current options: "
1464 << options_.ToString();
1465 return true;
1466}
1467
1468bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1469 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001470 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001473 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001474
1475 if (!VerifyUniquePayloadTypes(codecs)) {
1476 LOG(LS_ERROR) << "Codec payload types overlap.";
1477 return false;
1478 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479
1480 std::vector<AudioCodec> new_codecs;
1481 // Find all new codecs. We allow adding new codecs but don't allow changing
1482 // the payload type of codecs that is already configured since we might
1483 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001484 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001486 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1487 if (old_codec.id != codec.id) {
1488 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 return false;
1490 }
1491 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001492 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 }
1494 }
1495 if (new_codecs.empty()) {
1496 // There are no new codecs to configure. Already configured codecs are
1497 // never removed.
1498 return true;
1499 }
1500
1501 if (playout_) {
1502 // Receive codecs can not be changed while playing. So we temporarily
1503 // pause playout.
1504 PausePlayout();
1505 }
1506
solenberg26c8c912015-11-27 04:00:25 -08001507 bool result = true;
1508 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001509 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001510 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1511 LOG(LS_INFO) << ToString(codec);
1512 voe_codec.pltype = codec.id;
1513 for (const auto& ch : recv_streams_) {
1514 if (engine()->voe()->codec()->SetRecPayloadType(
1515 ch.second->channel(), voe_codec) == -1) {
1516 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1517 ToString(voe_codec));
1518 result = false;
1519 }
1520 }
1521 } else {
1522 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1523 result = false;
1524 break;
1525 }
1526 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001527 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 recv_codecs_ = codecs;
1529 }
1530
1531 if (desired_playout_ && !playout_) {
1532 ResumePlayout();
1533 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001534 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535}
1536
solenberg72e29d22016-03-08 06:35:16 -08001537// Utility function called from SetSendParameters() to extract current send
1538// codec settings from the given list of codecs (originally from SDP). Both send
1539// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001540bool WebRtcVoiceMediaChannel::SetSendCodecs(
1541 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001542 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001543 // TODO(solenberg): Validate input - that payload types don't overlap, are
1544 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001545 // redundant codecs etc - the same way it is done for
1546 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001547
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001548 // Find the DTMF telephone event "codec" payload type.
1549 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001550 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001551 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001552 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1553 return false;
1554 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001555 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1556 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001557 }
1558 }
1559
solenberg72e29d22016-03-08 06:35:16 -08001560 // Scan through the list to figure out the codec to use for sending, along
1561 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1562 // parameters.
1563 {
1564 SendCodecSpec send_codec_spec;
1565 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1566
1567 // Find send codec (the first non-telephone-event/CN codec).
1568 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1569 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1570 if (!codec) {
1571 LOG(LS_WARNING) << "Received empty list of codecs.";
1572 return false;
1573 }
1574
1575 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1576
1577 // This condition is apparently here because Opus does not support RED and
1578 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1579 // such limitations.
1580 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1581 if (send_codec_spec.red_payload_type == -1) {
1582 send_codec_spec.nack_enabled = HasNack(*codec);
1583 // For Opus as the send codec, we are to determine inband FEC, maximum
1584 // playback rate, and opus internal dtx.
1585 if (IsCodec(*codec, kOpusCodecName)) {
1586 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1587 &send_codec_spec.enable_codec_fec,
1588 &send_codec_spec.opus_max_playback_rate,
1589 &send_codec_spec.enable_opus_dtx);
1590 }
1591
1592 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1593 int ptime_ms = 0;
1594 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1595 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1596 &send_codec_spec.codec_inst, ptime_ms)) {
1597 LOG(LS_WARNING) << "Failed to set packet size for codec "
1598 << send_codec_spec.codec_inst.plname;
1599 return false;
1600 }
1601 }
1602 }
1603
1604 // Loop through the codecs list again to find the CN codec.
1605 // TODO(solenberg): Break out into a separate function?
1606 for (const AudioCodec& codec : codecs) {
1607 // Ignore codecs we don't know about. The negotiation step should prevent
1608 // this, but double-check to be sure.
1609 webrtc::CodecInst voe_codec = {0};
1610 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1611 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1612 continue;
1613 }
1614
1615 if (IsCodec(codec, kCnCodecName)) {
1616 // Turn voice activity detection/comfort noise on if supported.
1617 // Set the wideband CN payload type appropriately.
1618 // (narrowband always uses the static payload type 13).
1619 int cng_plfreq = -1;
1620 switch (codec.clockrate) {
1621 case 8000:
1622 case 16000:
1623 case 32000:
1624 cng_plfreq = codec.clockrate;
1625 break;
1626 default:
1627 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1628 << " not supported.";
1629 continue;
1630 }
1631 send_codec_spec.cng_payload_type = codec.id;
1632 send_codec_spec.cng_plfreq = cng_plfreq;
1633 break;
1634 }
1635 }
1636
1637 // Latch in the new state.
1638 send_codec_spec_ = std::move(send_codec_spec);
1639 }
1640
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001641 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001642 for (const auto& ch : send_streams_) {
skvlade0d46372016-04-07 22:59:22 -07001643 if (!SetSendCodecs(ch.second->channel(), ch.second->rtp_parameters())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001644 return false;
1645 }
1646 }
1647
solenberg72e29d22016-03-08 06:35:16 -08001648 // Set nack status on receive channels.
1649 if (!send_streams_.empty()) {
1650 for (const auto& kv : recv_streams_) {
1651 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1652 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001653 }
solenberg0a617e22015-10-20 15:49:38 -07001654
stefanba4c0e42016-02-04 04:12:24 -08001655 // Check if the transport cc feedback has changed on the preferred send codec,
1656 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001657 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1658 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1659 "codec has changed.";
1660 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1661 for (auto& kv : recv_streams_) {
1662 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1663 }
1664 }
1665
1666 return true;
1667}
1668
1669// Apply current codec settings to a single voe::Channel used for sending.
skvlade0d46372016-04-07 22:59:22 -07001670bool WebRtcVoiceMediaChannel::SetSendCodecs(
1671 int channel,
1672 const webrtc::RtpParameters& rtp_parameters) {
solenberg72e29d22016-03-08 06:35:16 -08001673 // Disable VAD, FEC, and RED unless we know the other side wants them.
1674 engine()->voe()->codec()->SetVADStatus(channel, false);
1675 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1676 engine()->voe()->rtp()->SetREDStatus(channel, false);
1677 engine()->voe()->codec()->SetFECStatus(channel, false);
1678
1679 if (send_codec_spec_.red_payload_type != -1) {
1680 // Enable redundant encoding of the specified codec. Treat any
1681 // failure as a fatal internal error.
1682 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1683 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1684 send_codec_spec_.red_payload_type) == -1) {
1685 LOG_RTCERR3(SetREDStatus, channel, true,
1686 send_codec_spec_.red_payload_type);
1687 return false;
1688 }
1689 }
1690
1691 SetNack(channel, send_codec_spec_.nack_enabled);
1692
1693 // Set the codec immediately, since SetVADStatus() depends on whether
1694 // the current codec is mono or stereo.
1695 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1696 return false;
1697 }
1698
1699 // FEC should be enabled after SetSendCodec.
1700 if (send_codec_spec_.enable_codec_fec) {
1701 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1702 << channel;
1703 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1704 // Enable codec internal FEC. Treat any failure as fatal internal error.
1705 LOG_RTCERR2(SetFECStatus, channel, true);
1706 return false;
1707 }
1708 }
1709
1710 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1711 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1712 // send codec has to be Opus.
1713
1714 // Set Opus internal DTX.
1715 LOG(LS_INFO) << "Attempt to "
1716 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1717 << " Opus DTX on channel "
1718 << channel;
1719 if (engine()->voe()->codec()->SetOpusDtx(channel,
1720 send_codec_spec_.enable_opus_dtx)) {
1721 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1722 return false;
1723 }
1724
1725 // If opus_max_playback_rate <= 0, the default maximum playback rate
1726 // (48 kHz) will be used.
1727 if (send_codec_spec_.opus_max_playback_rate > 0) {
1728 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1729 << send_codec_spec_.opus_max_playback_rate
1730 << " Hz on channel "
1731 << channel;
1732 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1733 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1734 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1735 send_codec_spec_.opus_max_playback_rate);
1736 return false;
stefanba4c0e42016-02-04 04:12:24 -08001737 }
1738 }
1739 }
skvlade0d46372016-04-07 22:59:22 -07001740 // TODO(solenberg): SetSendBitrate() yields another call to SetSendCodec().
1741 // Check if it is possible to fuse with the previous call in this function.
1742 SetChannelParameters(channel, rtp_parameters);
solenberg72e29d22016-03-08 06:35:16 -08001743
1744 // Set the CN payloadtype and the VAD status.
1745 if (send_codec_spec_.cng_payload_type != -1) {
1746 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1747 if (send_codec_spec_.cng_plfreq != 8000) {
1748 webrtc::PayloadFrequencies cn_freq;
1749 switch (send_codec_spec_.cng_plfreq) {
1750 case 16000:
1751 cn_freq = webrtc::kFreq16000Hz;
1752 break;
1753 case 32000:
1754 cn_freq = webrtc::kFreq32000Hz;
1755 break;
1756 default:
1757 RTC_NOTREACHED();
1758 return false;
1759 }
1760 if (engine()->voe()->codec()->SetSendCNPayloadType(
1761 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1762 LOG_RTCERR3(SetSendCNPayloadType, channel,
1763 send_codec_spec_.cng_payload_type, cn_freq);
1764 // TODO(ajm): This failure condition will be removed from VoE.
1765 // Restore the return here when we update to a new enough webrtc.
1766 //
1767 // Not returning false because the SetSendCNPayloadType will fail if
1768 // the channel is already sending.
1769 // This can happen if the remote description is applied twice, for
1770 // example in the case of ROAP on top of JSEP, where both side will
1771 // send the offer.
1772 }
1773 }
1774
1775 // Only turn on VAD if we have a CN payload type that matches the
1776 // clockrate for the codec we are going to use.
1777 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1778 send_codec_spec_.codec_inst.channels == 1) {
1779 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1780 // interaction between VAD and Opus FEC.
1781 LOG(LS_INFO) << "Enabling VAD";
1782 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1783 LOG_RTCERR2(SetVADStatus, channel, true);
1784 return false;
1785 }
1786 }
1787 }
solenberg0a617e22015-10-20 15:49:38 -07001788 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001789}
1790
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001791void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001793 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1795 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001796 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1798 }
1799}
1800
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001802 int channel, const webrtc::CodecInst& send_codec) {
1803 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1804 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1805
solenberg72e29d22016-03-08 06:35:16 -08001806 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001807 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1808 (send_codec == current_codec)) {
1809 // Codec is already configured, we can return without setting it again.
1810 return true;
1811 }
1812
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001813 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1814 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815 return false;
1816 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817 return true;
1818}
1819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1821 desired_playout_ = playout;
1822 return ChangePlayout(desired_playout_);
1823}
1824
1825bool WebRtcVoiceMediaChannel::PausePlayout() {
1826 return ChangePlayout(false);
1827}
1828
1829bool WebRtcVoiceMediaChannel::ResumePlayout() {
1830 return ChangePlayout(desired_playout_);
1831}
1832
1833bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001834 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001835 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001836 if (playout_ == playout) {
1837 return true;
1838 }
1839
solenberg7add0582015-11-20 09:59:34 -08001840 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001841 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001842 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001843 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001844 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 }
1846 }
solenberg1ac56142015-10-13 03:58:19 -07001847 playout_ = playout;
1848 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849}
1850
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001851void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001852 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001854 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001855 }
1856
solenbergd53a3f92016-04-14 13:56:37 -07001857 // Apply channel specific options, and initialize the ADM for recording (this
1858 // may take time on some platforms, e.g. Android).
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001859 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001860 engine()->ApplyOptions(options_);
solenbergd53a3f92016-04-14 13:56:37 -07001861
1862 // InitRecording() may return an error if the ADM is already recording.
1863 if (!engine()->adm()->RecordingIsInitialized() &&
1864 !engine()->adm()->Recording()) {
1865 if (engine()->adm()->InitRecording() != 0) {
1866 LOG(LS_WARNING) << "Failed to initialize recording";
1867 }
1868 }
solenberg63b34542015-09-29 06:06:31 -07001869 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001871 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001872 for (auto& kv : send_streams_) {
1873 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001875
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001876 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877}
1878
Peter Boström0c4e06b2015-10-07 12:23:21 +02001879bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1880 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001881 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001882 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001883 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001884 // TODO(solenberg): The state change should be fully rolled back if any one of
1885 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001886 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001887 return false;
1888 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001889 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001890 return false;
1891 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001892 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001893 return SetOptions(*options);
1894 }
1895 return true;
1896}
1897
solenberg0a617e22015-10-20 15:49:38 -07001898int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1899 int id = engine()->CreateVoEChannel();
1900 if (id == -1) {
1901 LOG_RTCERR0(CreateVoEChannel);
1902 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001903 }
solenberg0a617e22015-10-20 15:49:38 -07001904 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1905 LOG_RTCERR2(RegisterExternalTransport, id, this);
1906 engine()->voe()->base()->DeleteChannel(id);
1907 return -1;
1908 }
1909 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001910}
1911
solenberg7add0582015-11-20 09:59:34 -08001912bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001913 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1914 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1915 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001916 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1917 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return false;
1919 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001920 return true;
1921}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001922
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001923bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001924 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001925 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001926 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1927
1928 uint32_t ssrc = sp.first_ssrc();
1929 RTC_DCHECK(0 != ssrc);
1930
1931 if (GetSendChannelId(ssrc) != -1) {
1932 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001933 return false;
1934 }
1935
solenberg0a617e22015-10-20 15:49:38 -07001936 // Create a new channel for sending audio data.
1937 int channel = CreateVoEChannel();
1938 if (channel == -1) {
1939 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001940 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001941
solenbergc96df772015-10-21 13:01:53 -07001942 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001943 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001944 webrtc::AudioTransport* audio_transport =
1945 engine()->voe()->base()->audio_transport();
skvlade0d46372016-04-07 22:59:22 -07001946 WebRtcAudioSendStream* stream = new WebRtcAudioSendStream(
1947 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_);
1948 send_streams_.insert(std::make_pair(ssrc, stream));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001949
solenberg0a617e22015-10-20 15:49:38 -07001950 // Set the current codecs to be used for the new channel. We need to do this
1951 // after adding the channel to send_channels_, because of how max bitrate is
1952 // currently being configured by SetSendCodec().
skvlade0d46372016-04-07 22:59:22 -07001953 if (HasSendCodec() && !SetSendCodecs(channel, stream->rtp_parameters())) {
solenberg0a617e22015-10-20 15:49:38 -07001954 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001955 return false;
1956 }
1957
1958 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001959 // the first send channel make sure that all the receive channels are updated
1960 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001961 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001962 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001963 for (const auto& stream : recv_streams_) {
1964 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001965 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001966 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001967 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001968 }
solenberg0a617e22015-10-20 15:49:38 -07001969 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1970 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1971 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001972 }
1973 }
1974
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001975 send_streams_[ssrc]->SetSend(send_);
1976 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001977}
1978
Peter Boström0c4e06b2015-10-07 12:23:21 +02001979bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001980 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001981 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001982 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1983
solenbergc96df772015-10-21 13:01:53 -07001984 auto it = send_streams_.find(ssrc);
1985 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001986 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1987 << " which doesn't exist.";
1988 return false;
1989 }
1990
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001991 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001992
solenberg7add0582015-11-20 09:59:34 -08001993 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001994 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001995 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1996 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001997 delete it->second;
1998 send_streams_.erase(it);
1999 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07002000 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002001 }
solenbergc96df772015-10-21 13:01:53 -07002002 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002003 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07002004 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005 return true;
2006}
2007
2008bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002009 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002010 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002011 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2012
solenberg0b675462015-10-09 01:37:09 -07002013 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002014 return false;
2015 }
2016
solenberg7add0582015-11-20 09:59:34 -08002017 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002018 if (ssrc == 0) {
2019 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2020 return false;
2021 }
2022
solenberg1ac56142015-10-13 03:58:19 -07002023 // Remove the default receive stream if one had been created with this ssrc;
2024 // we'll recreate it then.
2025 if (IsDefaultRecvStream(ssrc)) {
2026 RemoveRecvStream(ssrc);
2027 }
solenberg0b675462015-10-09 01:37:09 -07002028
solenberg7add0582015-11-20 09:59:34 -08002029 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002030 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 return false;
2032 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002035 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 return false;
2038 }
Minyue2013aec2015-05-13 14:14:42 +02002039
solenberg1ac56142015-10-13 03:58:19 -07002040 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002041 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2042 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2043 voe_codec.pltype = -1;
2044 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2045 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2046 DeleteVoEChannel(channel);
2047 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 }
2049 }
2050
solenberg1ac56142015-10-13 03:58:19 -07002051 // Only enable those configured for this channel.
2052 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002053 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002054 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002055 voe_codec.pltype = codec.id;
2056 if (engine()->voe()->codec()->SetRecPayloadType(
2057 channel, voe_codec) == -1) {
2058 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002059 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002060 return false;
2061 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002062 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 }
solenberg8fb30c32015-10-13 03:06:58 -07002064
solenberg7add0582015-11-20 09:59:34 -08002065 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2066 if (send_channel != -1) {
2067 // Associate receive channel with first send channel (so the receive channel
2068 // can obtain RTT from the send channel)
2069 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2070 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2071 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002072 }
2073
stefanba4c0e42016-02-04 04:12:24 -08002074 recv_streams_.insert(std::make_pair(
2075 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002076 recv_transport_cc_enabled_,
2077 sp.sync_label, recv_rtp_extensions_,
2078 call_)));
solenberg7add0582015-11-20 09:59:34 -08002079
solenberg72e29d22016-03-08 06:35:16 -08002080 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002081 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002082
solenberg1ac56142015-10-13 03:58:19 -07002083 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002084}
2085
Peter Boström0c4e06b2015-10-07 12:23:21 +02002086bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002087 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002088 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002089 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2090
solenberg7add0582015-11-20 09:59:34 -08002091 const auto it = recv_streams_.find(ssrc);
2092 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002093 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2094 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002095 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002096 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097
solenberg1ac56142015-10-13 03:58:19 -07002098 // Deregister default channel, if that's the one being destroyed.
2099 if (IsDefaultRecvStream(ssrc)) {
2100 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002102
solenberg7add0582015-11-20 09:59:34 -08002103 const int channel = it->second->channel();
2104
2105 // Clean up and delete the receive stream+channel.
2106 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002107 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002108 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002109 delete it->second;
2110 recv_streams_.erase(it);
2111 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112}
2113
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002114bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2115 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002116 auto it = send_streams_.find(ssrc);
2117 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002118 if (source) {
2119 // Return an error if trying to set a valid source with an invalid ssrc.
2120 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002121 return false;
2122 }
2123
2124 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002125 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002126 }
2127
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002128 if (source) {
2129 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002130 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002131 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002132 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 return true;
2135}
2136
2137bool WebRtcVoiceMediaChannel::GetActiveStreams(
2138 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002139 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002141 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002142 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002144 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 }
2146 }
2147 return true;
2148}
2149
2150int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002151 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002152 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002153 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002154 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002155 }
2156 return highest;
2157}
2158
2159int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2160 int ret;
2161 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2162 // In case of error, log the info and continue
2163 LOG_RTCERR0(TimeSinceLastTyping);
2164 ret = -1;
2165 } else {
2166 ret *= 1000; // We return ms, webrtc returns seconds.
2167 }
2168 return ret;
2169}
2170
2171void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2172 int cost_per_typing, int reporting_threshold, int penalty_decay,
2173 int type_event_delay) {
2174 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2175 time_window, cost_per_typing,
2176 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2177 // In case of error, log the info and continue
2178 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2179 cost_per_typing, reporting_threshold, penalty_decay,
2180 type_event_delay);
2181 }
2182}
2183
solenberg4bac9c52015-10-09 02:32:53 -07002184bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002185 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002186 if (ssrc == 0) {
2187 default_recv_volume_ = volume;
2188 if (default_recv_ssrc_ == -1) {
2189 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002190 }
solenberg1ac56142015-10-13 03:58:19 -07002191 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2192 }
2193 int ch_id = GetReceiveChannelId(ssrc);
2194 if (ch_id < 0) {
2195 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2196 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 }
2198
solenberg1ac56142015-10-13 03:58:19 -07002199 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2200 volume)) {
2201 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2202 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 }
solenberg1ac56142015-10-13 03:58:19 -07002204 LOG(LS_INFO) << "SetOutputVolume to " << volume
2205 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 return true;
2207}
2208
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002210 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211}
2212
solenberg1d63dd02015-12-02 12:35:09 -08002213bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2214 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002215 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002216 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2217 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 return false;
2219 }
2220
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002221 // Figure out which WebRtcAudioSendStream to send the event on.
2222 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2223 if (it == send_streams_.end()) {
2224 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002225 return false;
2226 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002227 if (event < kMinTelephoneEventCode ||
2228 event > kMaxTelephoneEventCode) {
2229 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002230 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002232 if (duration < kMinTelephoneEventDuration ||
2233 duration > kMaxTelephoneEventDuration) {
2234 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2235 return false;
2236 }
2237 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238}
2239
wu@webrtc.orga9890802013-12-13 00:21:03 +00002240void WebRtcVoiceMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002241 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002242 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002243
solenberg1ac56142015-10-13 03:58:19 -07002244 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002245 if (!GetRtpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg1ac56142015-10-13 03:58:19 -07002246 return;
2247 }
2248
solenberg7e63ef02015-11-20 00:19:43 -08002249 // If we don't have a default channel, and the SSRC is unknown, create a
2250 // default channel.
2251 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002252 StreamParams sp;
2253 sp.ssrcs.push_back(ssrc);
2254 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2255 if (!AddRecvStream(sp)) {
2256 LOG(LS_WARNING) << "Could not create default receive stream.";
2257 return;
2258 }
2259 default_recv_ssrc_ = ssrc;
2260 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002261 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002262 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002263 new ProxySink(default_sink_.get()));
2264 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2265 }
solenberg1ac56142015-10-13 03:58:19 -07002266 }
2267
2268 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002269 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2270 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002271 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2272 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002273 packet->cdata(), packet->size(), webrtc_packet_time);
solenberg1ac56142015-10-13 03:58:19 -07002274 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002275 // If the SSRC is unknown here, route it to the default channel, if we have
2276 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2277 if (default_recv_ssrc_ == -1) {
2278 return;
2279 } else {
2280 ssrc = default_recv_ssrc_;
2281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 }
2283
solenberg1ac56142015-10-13 03:58:19 -07002284 // Find the channel to send this packet to. It must exist since webrtc::Call
2285 // was able to demux the packet.
2286 int channel = GetReceiveChannelId(ssrc);
2287 RTC_DCHECK(channel != -1);
2288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002290 engine()->voe()->network()->ReceivedRTPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002291 channel, packet->cdata(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292}
2293
wu@webrtc.orga9890802013-12-13 00:21:03 +00002294void WebRtcVoiceMediaChannel::OnRtcpReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002295 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002296 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002297
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002298 // Forward packet to Call as well.
2299 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2300 packet_time.not_before);
2301 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002302 packet->cdata(), packet->size(), webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002303
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002304 // Sending channels need all RTCP packets with feedback information.
2305 // Even sender reports can contain attached report blocks.
2306 // Receiving channels need sender reports in order to create
2307 // correct receiver reports.
2308 int type = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002309 if (!GetRtcpType(packet->cdata(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002310 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2311 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312 }
2313
solenberg0b675462015-10-09 01:37:09 -07002314 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002315 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002316 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002317 if (!GetRtcpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg0b675462015-10-09 01:37:09 -07002318 return;
2319 }
2320 int recv_channel_id = GetReceiveChannelId(ssrc);
2321 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002322 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002323 recv_channel_id, packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324 }
2325 }
2326
2327 // SR may continue RR and any RR entry may correspond to any one of the send
2328 // channels. So all RTCP packets must be forwarded all send channels. VoE
2329 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002330 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002331 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002332 ch.second->channel(), packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334}
2335
Honghai Zhangcc411c02016-03-29 17:27:21 -07002336void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2337 const std::string& transport_name,
2338 const NetworkRoute& network_route) {
2339 // TODO(honghaiz): uncomment this once the function in call is implemented.
2340 // call_->OnNetworkRouteChanged(transport_name, network_route);
2341}
2342
Peter Boström0c4e06b2015-10-07 12:23:21 +02002343bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002344 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002345 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002346 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2348 return false;
2349 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002350 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2351 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 return false;
2353 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002354 // We set the AGC to mute state only when all the channels are muted.
2355 // This implementation is not ideal, instead we should signal the AGC when
2356 // the mic channel is muted/unmuted. We can't do it today because there
2357 // is no good way to know which stream is mapping to the mic channel.
2358 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002359 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002360 if (!all_muted) {
2361 break;
2362 }
2363 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002364 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002365 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002366 return false;
2367 }
2368 }
2369
2370 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002371 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002372 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002373 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 return true;
2375}
2376
skvlade0d46372016-04-07 22:59:22 -07002377bool WebRtcVoiceMediaChannel::SetSendBitrate(int bps) {
2378 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrate.";
2379 send_bitrate_bps_ = bps;
2380
2381 for (const auto& kv : send_streams_) {
2382 if (!SetChannelParameters(kv.second->channel(),
2383 kv.second->rtp_parameters())) {
2384 return false;
2385 }
2386 }
2387 return true;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002388}
2389
skvlade0d46372016-04-07 22:59:22 -07002390bool WebRtcVoiceMediaChannel::SetChannelParameters(
2391 int channel,
2392 const webrtc::RtpParameters& parameters) {
2393 RTC_CHECK_EQ(1UL, parameters.encodings.size());
2394 return SetSendBitrate(
2395 channel,
2396 MinPositive(send_bitrate_bps_, parameters.encodings[0].max_bitrate_bps));
2397}
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002398
skvlade0d46372016-04-07 22:59:22 -07002399bool WebRtcVoiceMediaChannel::SetSendBitrate(int channel, int bps) {
2400 // Bitrate is auto by default.
2401 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2402 // SetMaxSendBandwith(0), the second call removes the previous limit.
2403 if (bps <= 0)
2404 return true;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002405
solenberg72e29d22016-03-08 06:35:16 -08002406 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002407 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002408 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002409 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 }
2411
solenberg72e29d22016-03-08 06:35:16 -08002412 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002413 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414
2415 if (is_multi_rate) {
2416 // If codec is multi-rate then just set the bitrate.
2417 codec.rate = bps;
skvlade0d46372016-04-07 22:59:22 -07002418 if (!SetSendCodec(channel, codec)) {
2419 LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate "
2420 << bps << " bps.";
2421 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 }
2423 return true;
2424 } else {
2425 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2426 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2427 // fixed bitrate then ignore.
2428 if (bps < codec.rate) {
2429 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2430 << " to bitrate " << bps << " bps"
2431 << ", requires at least " << codec.rate << " bps.";
2432 return false;
2433 }
2434 return true;
2435 }
2436}
2437
skvlad7a43d252016-03-22 15:32:27 -07002438void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2439 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2440 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2441 call_->SignalChannelNetworkState(
2442 webrtc::MediaType::AUDIO,
2443 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2444}
2445
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002447 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002448 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002449 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002450
solenberg85a04962015-10-27 03:35:21 -07002451 // Get SSRC and stats for each sender.
2452 RTC_DCHECK(info->senders.size() == 0);
2453 for (const auto& stream : send_streams_) {
2454 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002455 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002456 sinfo.add_ssrc(stats.local_ssrc);
2457 sinfo.bytes_sent = stats.bytes_sent;
2458 sinfo.packets_sent = stats.packets_sent;
2459 sinfo.packets_lost = stats.packets_lost;
2460 sinfo.fraction_lost = stats.fraction_lost;
2461 sinfo.codec_name = stats.codec_name;
2462 sinfo.ext_seqnum = stats.ext_seqnum;
2463 sinfo.jitter_ms = stats.jitter_ms;
2464 sinfo.rtt_ms = stats.rtt_ms;
2465 sinfo.audio_level = stats.audio_level;
2466 sinfo.aec_quality_min = stats.aec_quality_min;
2467 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2468 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2469 sinfo.echo_return_loss = stats.echo_return_loss;
2470 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002471 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002472 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473 }
2474
solenberg85a04962015-10-27 03:35:21 -07002475 // Get SSRC and stats for each receiver.
2476 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002477 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002478 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2479 VoiceReceiverInfo rinfo;
2480 rinfo.add_ssrc(stats.remote_ssrc);
2481 rinfo.bytes_rcvd = stats.bytes_rcvd;
2482 rinfo.packets_rcvd = stats.packets_rcvd;
2483 rinfo.packets_lost = stats.packets_lost;
2484 rinfo.fraction_lost = stats.fraction_lost;
2485 rinfo.codec_name = stats.codec_name;
2486 rinfo.ext_seqnum = stats.ext_seqnum;
2487 rinfo.jitter_ms = stats.jitter_ms;
2488 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2489 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2490 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2491 rinfo.audio_level = stats.audio_level;
2492 rinfo.expand_rate = stats.expand_rate;
2493 rinfo.speech_expand_rate = stats.speech_expand_rate;
2494 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2495 rinfo.accelerate_rate = stats.accelerate_rate;
2496 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2497 rinfo.decoding_calls_to_silence_generator =
2498 stats.decoding_calls_to_silence_generator;
2499 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2500 rinfo.decoding_normal = stats.decoding_normal;
2501 rinfo.decoding_plc = stats.decoding_plc;
2502 rinfo.decoding_cng = stats.decoding_cng;
2503 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2504 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2505 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002506 }
2507
2508 return true;
2509}
2510
Tommif888bb52015-12-12 01:37:01 +01002511void WebRtcVoiceMediaChannel::SetRawAudioSink(
2512 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002513 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002514 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002515 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2516 << " " << (sink ? "(ptr)" : "NULL");
2517 if (ssrc == 0) {
2518 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002519 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002520 sink ? new ProxySink(sink.get()) : nullptr);
2521 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2522 }
2523 default_sink_ = std::move(sink);
2524 return;
2525 }
Tommif888bb52015-12-12 01:37:01 +01002526 const auto it = recv_streams_.find(ssrc);
2527 if (it == recv_streams_.end()) {
2528 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2529 return;
2530 }
deadbeef2d110be2016-01-13 12:00:26 -08002531 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002532}
2533
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002535 unsigned int ulevel = 0;
2536 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2538}
2539
Peter Boström0c4e06b2015-10-07 12:23:21 +02002540int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002541 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002542 const auto it = recv_streams_.find(ssrc);
2543 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002544 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002545 }
solenberg1ac56142015-10-13 03:58:19 -07002546 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002547}
2548
Peter Boström0c4e06b2015-10-07 12:23:21 +02002549int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002550 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002551 const auto it = send_streams_.find(ssrc);
2552 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002553 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002554 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002555 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002556}
2557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2559 if (playout) {
2560 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2561 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2562 LOG_RTCERR1(StartPlayout, channel);
2563 return false;
2564 }
2565 } else {
2566 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2567 engine()->voe()->base()->StopPlayout(channel);
2568 }
2569 return true;
2570}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571} // namespace cricket
2572
2573#endif // HAVE_WEBRTC_VOICE