blob: c11993d550586f186f8a484d55f58b297220b465 [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"
kwiberg4485ffb2016-04-26 08:14:39 -070025#include "webrtc/base/constructormagic.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000026#include "webrtc/base/helpers.h"
27#include "webrtc/base/logging.h"
28#include "webrtc/base/stringencode.h"
29#include "webrtc/base/stringutils.h"
Peter Boströmca8b4042016-03-08 14:24:13 -080030#include "webrtc/base/trace_event.h"
ivoc112a3d82015-10-16 02:22:18 -070031#include "webrtc/call/rtc_event_log.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000032#include "webrtc/common.h"
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -080033#include "webrtc/media/base/audiosource.h"
kjellanderf4752772016-03-02 05:42:30 -080034#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080035#include "webrtc/media/base/streamparams.h"
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010036#include "webrtc/media/engine/webrtcmediaengine.h"
37#include "webrtc/media/engine/webrtcvoe.h"
solenberg26c8c912015-11-27 04:00:25 -080038#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000039#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010040#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080041#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070044namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
solenbergbd138382015-11-20 16:08:07 -080046const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
47 webrtc::kTraceWarning | webrtc::kTraceError |
48 webrtc::kTraceCritical;
49const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
50 webrtc::kTraceInfo;
51
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052// On Windows Vista and newer, Microsoft introduced the concept of "Default
53// Communications Device". This means that there are two types of default
54// devices (old Wave Audio style default and Default Communications Device).
55//
56// On Windows systems which only support Wave Audio style default, uses either
57// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070059const int kDefaultAudioDeviceId = -1;
solenberg8ad582d2016-03-16 09:34:56 -070060#elif !defined(WEBRTC_IOS)
solenbergd97ec302015-10-07 01:40:33 -070061const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062#endif
63
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064// Parameter used for NACK.
65// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070066const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000067
68// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000069// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000070
71// Recommended bitrates:
72// 8-12 kb/s for NB speech,
73// 16-20 kb/s for WB speech,
74// 28-40 kb/s for FB speech,
75// 48-64 kb/s for FB mono music, and
76// 64-128 kb/s for FB stereo music.
77// The current implementation applies the following values to mono signals,
78// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070079const int kOpusBitrateNb = 12000;
80const int kOpusBitrateWb = 20000;
81const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000082
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000083// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -070084const int kOpusMinBitrate = 6000;
85const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000086
wu@webrtc.orgde305012013-10-31 15:40:38 +000087// Default audio dscp value.
88// See http://tools.ietf.org/html/rfc2474 for details.
89// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -070090const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000091
Fredrik Solenbergb5727682015-12-04 15:22:19 +010092// Constants from voice_engine_defines.h.
93const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
94const int kMaxTelephoneEventCode = 255;
95const int kMinTelephoneEventDuration = 100;
96const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
97
solenberg31642aa2016-03-14 08:00:37 -070098const int kMinPayloadType = 0;
99const int kMaxPayloadType = 127;
100
deadbeef884f5852016-01-15 09:20:04 -0800101class ProxySink : public webrtc::AudioSinkInterface {
102 public:
103 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
104
105 void OnData(const Data& audio) override { sink_->OnData(audio); }
106
107 private:
108 webrtc::AudioSinkInterface* sink_;
109};
110
solenberg0b675462015-10-09 01:37:09 -0700111bool ValidateStreamParams(const StreamParams& sp) {
112 if (sp.ssrcs.empty()) {
113 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
114 return false;
115 }
116 if (sp.ssrcs.size() > 1) {
117 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
118 return false;
119 }
120 return true;
121}
122
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700124std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 std::stringstream ss;
126 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
127 << " (" << codec.id << ")";
128 return ss.str();
129}
Minyue Li7100dcd2015-03-27 05:05:59 +0100130
solenbergd97ec302015-10-07 01:40:33 -0700131std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 std::stringstream ss;
133 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
134 << " (" << codec.pltype << ")";
135 return ss.str();
136}
137
solenbergd97ec302015-10-07 01:40:33 -0700138bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100139 return (_stricmp(codec.name.c_str(), ref_name) == 0);
140}
141
solenbergd97ec302015-10-07 01:40:33 -0700142bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100143 return (_stricmp(codec.plname, ref_name) == 0);
144}
145
solenbergd97ec302015-10-07 01:40:33 -0700146bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800147 const AudioCodec& codec,
148 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200149 for (const AudioCodec& c : codecs) {
150 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200152 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153 }
154 return true;
155 }
156 }
157 return false;
158}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000159
solenberg0b675462015-10-09 01:37:09 -0700160bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
161 if (codecs.empty()) {
162 return true;
163 }
164 std::vector<int> payload_types;
165 for (const AudioCodec& codec : codecs) {
166 payload_types.push_back(codec.id);
167 }
168 std::sort(payload_types.begin(), payload_types.end());
169 auto it = std::unique(payload_types.begin(), payload_types.end());
170 return it == payload_types.end();
171}
172
Minyue Li7100dcd2015-03-27 05:05:59 +0100173// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800174bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100175 int value;
176 return codec.GetParam(feature, &value) && value == 1;
177}
178
179// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
180// otherwise. If the value (either from params or codec.bitrate) <=0, use the
181// default configuration. If the value is beyond feasible bit rate of Opus,
182// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700183int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100184 int bitrate = 0;
185 bool use_param = true;
186 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
187 bitrate = codec.bitrate;
188 use_param = false;
189 }
190 if (bitrate <= 0) {
191 if (max_playback_rate <= 8000) {
192 bitrate = kOpusBitrateNb;
193 } else if (max_playback_rate <= 16000) {
194 bitrate = kOpusBitrateWb;
195 } else {
196 bitrate = kOpusBitrateFb;
197 }
198
199 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
200 bitrate *= 2;
201 }
202 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
203 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
204 std::string rate_source =
205 use_param ? "Codec parameter \"maxaveragebitrate\"" :
206 "Supplied Opus bitrate";
207 LOG(LS_WARNING) << rate_source
208 << " is invalid and is replaced by: "
209 << bitrate;
210 }
211 return bitrate;
212}
213
214// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
215// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700216int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100217 int value;
218 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
219 return value;
220 }
221 return kOpusDefaultMaxPlaybackRate;
222}
223
solenbergd97ec302015-10-07 01:40:33 -0700224void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100225 bool* enable_codec_fec, int* max_playback_rate,
226 bool* enable_codec_dtx) {
227 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
228 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
229 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
230
231 // If OPUS, change what we send according to the "stereo" codec
232 // parameter, and not the "channels" parameter. We set
233 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
234 // the bitrate is not specified, i.e. is <= zero, we set it to the
235 // appropriate default value for mono or stereo Opus.
236
237 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
238 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
239}
240
solenberg566ef242015-11-06 15:34:49 -0800241webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
242 webrtc::AudioState::Config config;
243 config.voice_engine = voe_wrapper->engine();
244 return config;
245}
246
solenberg26c8c912015-11-27 04:00:25 -0800247class WebRtcVoiceCodecs final {
248 public:
249 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
250 // list and add a test which verifies VoE supports the listed codecs.
251 static std::vector<AudioCodec> SupportedCodecs() {
solenberg26c8c912015-11-27 04:00:25 -0800252 std::vector<AudioCodec> result;
deadbeef67cf2c12016-04-13 10:07:16 -0700253 // Iterate first over our preferred codecs list, so that the results are
254 // added in order of preference.
255 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
256 const CodecPref* pref = &kCodecPrefs[i];
257 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
258 // Change the sample rate of G722 to 8000 to match SDP.
259 MaybeFixupG722(&voe_codec, 8000);
260 // Skip uncompressed formats.
261 if (IsCodec(voe_codec, kL16CodecName)) {
262 continue;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000263 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000264
deadbeef67cf2c12016-04-13 10:07:16 -0700265 if (!IsCodec(voe_codec, pref->name) ||
266 pref->clockrate != voe_codec.plfreq ||
267 pref->channels != voe_codec.channels) {
268 // Not a match.
269 continue;
270 }
271
272 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
273 voe_codec.rate, voe_codec.channels);
274 LOG(LS_INFO) << "Adding supported codec: " << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100275 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000276 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000277 codec.bitrate = 0;
278 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100279 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000280 // Only add fmtp parameters that differ from the spec.
281 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
282 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000283 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000284 }
285 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
286 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000287 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000288 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000289 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800290 codec.AddFeedbackParam(
291 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000292
293 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000294 // when they can be set to values other than the default.
295 }
solenberg26c8c912015-11-27 04:00:25 -0800296 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000297 }
298 }
solenberg26c8c912015-11-27 04:00:25 -0800299 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000300 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000301
solenberg26c8c912015-11-27 04:00:25 -0800302 static bool ToCodecInst(const AudioCodec& in,
303 webrtc::CodecInst* out) {
304 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
305 // Change the sample rate of G722 to 8000 to match SDP.
306 MaybeFixupG722(&voe_codec, 8000);
307 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
deadbeef67cf2c12016-04-13 10:07:16 -0700308 voe_codec.rate, voe_codec.channels);
solenberg26c8c912015-11-27 04:00:25 -0800309 bool multi_rate = IsCodecMultiRate(voe_codec);
310 // Allow arbitrary rates for ISAC to be specified.
311 if (multi_rate) {
312 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
313 codec.bitrate = 0;
314 }
315 if (codec.Matches(in)) {
316 if (out) {
317 // Fixup the payload type.
318 voe_codec.pltype = in.id;
319
320 // Set bitrate if specified.
321 if (multi_rate && in.bitrate != 0) {
322 voe_codec.rate = in.bitrate;
323 }
324
325 // Reset G722 sample rate to 16000 to match WebRTC.
326 MaybeFixupG722(&voe_codec, 16000);
327
328 // Apply codec-specific settings.
329 if (IsCodec(codec, kIsacCodecName)) {
330 // If ISAC and an explicit bitrate is not specified,
331 // enable auto bitrate adjustment.
332 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
333 }
334 *out = voe_codec;
335 }
336 return true;
337 }
338 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000339 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000340 }
solenberg26c8c912015-11-27 04:00:25 -0800341
342 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
343 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
344 if (IsCodec(codec, kCodecPrefs[i].name) &&
345 kCodecPrefs[i].clockrate == codec.plfreq) {
346 return kCodecPrefs[i].is_multi_rate;
347 }
348 }
349 return false;
350 }
351
352 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
353 // codec pacsize if it's valid, or we will pick the next smallest value we
354 // support.
355 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
356 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
357 for (const CodecPref& codec_pref : kCodecPrefs) {
358 if ((IsCodec(*codec, codec_pref.name) &&
359 codec_pref.clockrate == codec->plfreq) ||
360 IsCodec(*codec, kG722CodecName)) {
361 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
362 if (packet_size_ms) {
363 // Convert unit from milli-seconds to samples.
364 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
365 return true;
366 }
367 }
368 }
369 return false;
370 }
371
stefanba4c0e42016-02-04 04:12:24 -0800372 static const AudioCodec* GetPreferredCodec(
373 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800374 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800375 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800376 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800377 RTC_DCHECK(red_payload_type);
378 // Select the preferred send codec (the first non-telephone-event/CN codec).
379 for (const AudioCodec& codec : codecs) {
380 *red_payload_type = -1;
381 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
382 // Skip telephone-event/CN codec, which will be handled later.
383 continue;
384 }
385
386 // We'll use the first codec in the list to actually send audio data.
387 // Be sure to use the payload type requested by the remote side.
388 // "red", for RED audio, is a special case where the actual codec to be
389 // used is specified in params.
390 const AudioCodec* found_codec = &codec;
391 if (IsCodec(*found_codec, kRedCodecName)) {
392 // Parse out the RED parameters. If we fail, just ignore RED;
393 // we don't support all possible params/usage scenarios.
394 *red_payload_type = codec.id;
395 found_codec = GetRedSendCodec(*found_codec, codecs);
396 if (!found_codec) {
397 continue;
398 }
399 }
400 // Ignore codecs we don't know about. The negotiation step should prevent
401 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800402 webrtc::CodecInst voe_codec = {0};
403 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800404 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
405 continue;
406 }
solenberg72e29d22016-03-08 06:35:16 -0800407 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800408 return found_codec;
409 }
410 return nullptr;
411 }
412
solenberg26c8c912015-11-27 04:00:25 -0800413 private:
414 static const int kMaxNumPacketSize = 6;
415 struct CodecPref {
416 const char* name;
417 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800418 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800419 int payload_type;
420 bool is_multi_rate;
421 int packet_sizes_ms[kMaxNumPacketSize];
422 };
423 // Note: keep the supported packet sizes in ascending order.
424 static const CodecPref kCodecPrefs[12];
425
426 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
427 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
428 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
429 if (packet_size_ms && packet_size_ms <= ptime_ms) {
430 selected_packet_size_ms = packet_size_ms;
431 }
432 }
433 return selected_packet_size_ms;
434 }
435
436 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
437 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
438 // codec.
439 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
440 if (IsCodec(*voe_codec, kG722CodecName)) {
441 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
442 // has changed, and this special case is no longer needed.
443 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
444 voe_codec->plfreq = new_plfreq;
445 }
446 }
stefanba4c0e42016-02-04 04:12:24 -0800447
448 static const AudioCodec* GetRedSendCodec(
449 const AudioCodec& red_codec,
450 const std::vector<AudioCodec>& all_codecs) {
451 // Get the RED encodings from the parameter with no name. This may
452 // change based on what is discussed on the Jingle list.
453 // The encoding parameter is of the form "a/b"; we only support where
454 // a == b. Verify this and parse out the value into red_pt.
455 // If the parameter value is absent (as it will be until we wire up the
456 // signaling of this message), use the second codec specified (i.e. the
457 // one after "red") as the encoding parameter.
458 int red_pt = -1;
459 std::string red_params;
460 CodecParameterMap::const_iterator it = red_codec.params.find("");
461 if (it != red_codec.params.end()) {
462 red_params = it->second;
463 std::vector<std::string> red_pts;
464 if (rtc::split(red_params, '/', &red_pts) != 2 ||
465 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
466 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
467 return nullptr;
468 }
469 } else if (red_codec.params.empty()) {
470 LOG(LS_WARNING) << "RED params not present, using defaults";
471 if (all_codecs.size() > 1) {
472 red_pt = all_codecs[1].id;
473 }
474 }
475
476 // Try to find red_pt in |codecs|.
477 for (const AudioCodec& codec : all_codecs) {
478 if (codec.id == red_pt) {
479 return &codec;
480 }
481 }
482 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
483 return nullptr;
484 }
solenberg26c8c912015-11-27 04:00:25 -0800485};
486
487const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
488 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
489 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
490 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
491 // G722 should be advertised as 8000 Hz because of the RFC "bug".
492 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
493 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
494 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
495 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
496 { kCnCodecName, 32000, 1, 106, false, { } },
497 { kCnCodecName, 16000, 1, 105, false, { } },
498 { kCnCodecName, 8000, 1, 13, false, { } },
499 { kRedCodecName, 8000, 1, 127, false, { } },
500 { kDtmfCodecName, 8000, 1, 126, false, { } },
501};
502} // namespace {
503
504bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
505 webrtc::CodecInst* out) {
506 return WebRtcVoiceCodecs::ToCodecInst(in, out);
507}
508
solenbergff976312016-03-30 23:28:51 -0700509WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm)
510 : WebRtcVoiceEngine(adm, new VoEWrapper()) {
511 audio_state_ = webrtc::AudioState::Create(MakeAudioStateConfig(voe()));
solenberg26c8c912015-11-27 04:00:25 -0800512}
513
solenbergff976312016-03-30 23:28:51 -0700514WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm,
515 VoEWrapper* voe_wrapper)
516 : adm_(adm), voe_wrapper_(voe_wrapper) {
solenberg26c8c912015-11-27 04:00:25 -0800517 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700518 LOG(LS_INFO) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
519 RTC_DCHECK(voe_wrapper);
solenberg26c8c912015-11-27 04:00:25 -0800520
521 signal_thread_checker_.DetachFromThread();
solenberg26c8c912015-11-27 04:00:25 -0800522
523 // Load our audio codec list.
solenbergff976312016-03-30 23:28:51 -0700524 LOG(LS_INFO) << "Supported codecs in order of preference:";
solenberg26c8c912015-11-27 04:00:25 -0800525 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
solenbergff976312016-03-30 23:28:51 -0700526 for (const AudioCodec& codec : codecs_) {
527 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000529
solenbergff976312016-03-30 23:28:51 -0700530 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531
solenbergff976312016-03-30 23:28:51 -0700532 // Temporarily turn logging level up for the Init() call.
533 webrtc::Trace::SetTraceCallback(this);
solenbergbd138382015-11-20 16:08:07 -0800534 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800535 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
solenbergff976312016-03-30 23:28:51 -0700536 RTC_CHECK_EQ(0, voe_wrapper_->base()->Init(adm_.get()));
solenbergbd138382015-11-20 16:08:07 -0800537 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000538
solenbergff976312016-03-30 23:28:51 -0700539 // No ADM supplied? Get the default one from VoE.
540 if (!adm_) {
541 adm_ = voe_wrapper_->base()->audio_device_module();
542 }
543 RTC_DCHECK(adm_);
544
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800546 // calling ApplyOptions or the default will be overwritten.
solenbergff976312016-03-30 23:28:51 -0700547 int error = voe_wrapper_->processing()->GetAgcConfig(default_agc_config_);
548 RTC_DCHECK_EQ(0, error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000549
solenberg0f7d2932016-01-15 01:40:39 -0800550 // Set default engine options.
551 {
552 AudioOptions options;
553 options.echo_cancellation = rtc::Optional<bool>(true);
554 options.auto_gain_control = rtc::Optional<bool>(true);
555 options.noise_suppression = rtc::Optional<bool>(true);
556 options.highpass_filter = rtc::Optional<bool>(true);
557 options.stereo_swapping = rtc::Optional<bool>(false);
558 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
559 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
560 options.typing_detection = rtc::Optional<bool>(true);
561 options.adjust_agc_delta = rtc::Optional<int>(0);
562 options.experimental_agc = rtc::Optional<bool>(false);
563 options.extended_filter_aec = rtc::Optional<bool>(false);
564 options.delay_agnostic_aec = rtc::Optional<bool>(false);
565 options.experimental_ns = rtc::Optional<bool>(false);
solenbergff976312016-03-30 23:28:51 -0700566 bool error = ApplyOptions(options);
567 RTC_DCHECK(error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568 }
569
solenberg246b8172015-12-08 09:50:23 -0800570 SetDefaultDevices();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000571}
572
solenbergff976312016-03-30 23:28:51 -0700573WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800574 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700575 LOG(LS_INFO) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 StopAecDump();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000577 voe_wrapper_->base()->Terminate();
solenbergff976312016-03-30 23:28:51 -0700578 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000579}
580
solenberg566ef242015-11-06 15:34:49 -0800581rtc::scoped_refptr<webrtc::AudioState>
582 WebRtcVoiceEngine::GetAudioState() const {
583 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
584 return audio_state_;
585}
586
nisse51542be2016-02-12 02:27:06 -0800587VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
588 webrtc::Call* call,
589 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200590 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800591 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800592 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000593}
594
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000595bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800596 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700597 LOG(LS_INFO) << "WebRtcVoiceEngine::ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800598 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800599
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000600 // kEcConference is AEC with high suppression.
601 webrtc::EcModes ec_mode = webrtc::kEcConference;
602 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
603 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
604 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700605 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000606 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700607 << *options.aecm_generate_comfort_noise
608 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000609 }
610
kjellanderfcfc8042016-01-14 11:01:09 -0800611#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000612 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100613 options.echo_cancellation = rtc::Optional<bool>(false);
614 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200615 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000616#elif defined(ANDROID)
617 ec_mode = webrtc::kEcAecm;
618#endif
619
kjellanderfcfc8042016-01-14 11:01:09 -0800620#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000621 // Set the AGC mode for iOS as well despite disabling it above, to avoid
622 // unsupported configuration errors from webrtc.
623 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100624 options.typing_detection = rtc::Optional<bool>(false);
625 options.experimental_agc = rtc::Optional<bool>(false);
626 options.extended_filter_aec = rtc::Optional<bool>(false);
627 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000628#endif
629
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100630 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
631 // where the feature is not supported.
632 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800633#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700634 if (options.delay_agnostic_aec) {
635 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100636 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100637 options.echo_cancellation = rtc::Optional<bool>(true);
638 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100639 ec_mode = webrtc::kEcConference;
640 }
641 }
642#endif
643
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
645
kwiberg102c6a62015-10-30 02:47:38 -0700646 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000647 // Check if platform supports built-in EC. Currently only supported on
648 // Android and in combination with Java based audio layer.
649 // TODO(henrika): investigate possibility to support built-in EC also
650 // in combination with Open SL ES audio.
solenberg5b5129a2016-04-08 05:35:48 -0700651 const bool built_in_aec = adm()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200652 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200653 // Built-in EC exists on this device and use_delay_agnostic_aec is not
654 // overriding it. Enable/Disable it according to the echo_cancellation
655 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200656 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700657 *options.echo_cancellation && !use_delay_agnostic_aec;
solenberg5b5129a2016-04-08 05:35:48 -0700658 if (adm()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
Bjorn Volcker73f72102015-06-03 14:50:15 +0200659 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100660 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000661 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100662 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000663 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
664 }
665 }
kwiberg102c6a62015-10-30 02:47:38 -0700666 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
667 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000668 return false;
669 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700670 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200671 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000672 }
673#if !defined(ANDROID)
674 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700675 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
676 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000677 return false;
678 }
679#endif
680 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700681 bool cn = options.aecm_generate_comfort_noise.value_or(false);
682 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
683 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000684 return false;
685 }
686 }
687 }
688
kwiberg102c6a62015-10-30 02:47:38 -0700689 if (options.auto_gain_control) {
solenberg5b5129a2016-04-08 05:35:48 -0700690 const bool built_in_agc = adm()->BuiltInAGCIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200691 if (built_in_agc) {
solenberg5b5129a2016-04-08 05:35:48 -0700692 if (adm()->EnableBuiltInAGC(*options.auto_gain_control) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700693 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200694 // Disable internal software AGC if built-in AGC is enabled,
695 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100696 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200697 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
698 }
699 }
kwiberg102c6a62015-10-30 02:47:38 -0700700 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
701 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000702 return false;
703 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700704 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
705 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000706 }
707 }
708
kwiberg102c6a62015-10-30 02:47:38 -0700709 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
710 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000711 // Override default_agc_config_. Generally, an unset option means "leave
712 // the VoE bits alone" in this function, so we want whatever is set to be
713 // stored as the new "default". If we didn't, then setting e.g.
714 // tx_agc_target_dbov would reset digital compression gain and limiter
715 // settings.
716 // Also, if we don't update default_agc_config_, then adjust_agc_delta
717 // would be an offset from the original values, and not whatever was set
718 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700719 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
720 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000721 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700722 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000723 default_agc_config_.digitalCompressionGaindB);
724 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700725 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000726 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
727 LOG_RTCERR3(SetAgcConfig,
728 default_agc_config_.targetLeveldBOv,
729 default_agc_config_.digitalCompressionGaindB,
730 default_agc_config_.limiterEnable);
731 return false;
732 }
733 }
734
kwiberg102c6a62015-10-30 02:47:38 -0700735 if (options.noise_suppression) {
solenberg5b5129a2016-04-08 05:35:48 -0700736 const bool built_in_ns = adm()->BuiltInNSIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200737 if (built_in_ns) {
solenberg5b5129a2016-04-08 05:35:48 -0700738 if (adm()->EnableBuiltInNS(*options.noise_suppression) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700739 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200740 // Disable internal software NS if built-in NS is enabled,
741 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100742 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200743 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
744 }
745 }
kwiberg102c6a62015-10-30 02:47:38 -0700746 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
747 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000748 return false;
749 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700750 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200751 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000752 }
753 }
754
kwiberg102c6a62015-10-30 02:47:38 -0700755 if (options.highpass_filter) {
756 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
757 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
758 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000759 return false;
760 }
761 }
762
kwiberg102c6a62015-10-30 02:47:38 -0700763 if (options.stereo_swapping) {
764 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
765 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
766 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
767 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000768 return false;
769 }
770 }
771
kwiberg102c6a62015-10-30 02:47:38 -0700772 if (options.audio_jitter_buffer_max_packets) {
773 LOG(LS_INFO) << "NetEq capacity is "
774 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200775 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700776 new webrtc::NetEqCapacityConfig(
777 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200778 }
779
kwiberg102c6a62015-10-30 02:47:38 -0700780 if (options.audio_jitter_buffer_fast_accelerate) {
781 LOG(LS_INFO) << "NetEq fast mode? "
782 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200783 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700784 new webrtc::NetEqFastAccelerate(
785 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200786 }
787
kwiberg102c6a62015-10-30 02:47:38 -0700788 if (options.typing_detection) {
789 LOG(LS_INFO) << "Typing detection is enabled? "
790 << *options.typing_detection;
791 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000792 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700793 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000794 }
795 }
796
kwiberg102c6a62015-10-30 02:47:38 -0700797 if (options.adjust_agc_delta) {
798 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
799 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000800 return false;
801 }
802 }
803
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000804 webrtc::Config config;
805
kwiberg102c6a62015-10-30 02:47:38 -0700806 if (options.delay_agnostic_aec)
807 delay_agnostic_aec_ = options.delay_agnostic_aec;
808 if (delay_agnostic_aec_) {
809 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700810 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700811 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100812 }
813
kwiberg102c6a62015-10-30 02:47:38 -0700814 if (options.extended_filter_aec) {
815 extended_filter_aec_ = options.extended_filter_aec;
816 }
817 if (extended_filter_aec_) {
818 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200819 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700820 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000821 }
822
kwiberg102c6a62015-10-30 02:47:38 -0700823 if (options.experimental_ns) {
824 experimental_ns_ = options.experimental_ns;
825 }
826 if (experimental_ns_) {
827 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000828 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700829 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000830 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000831
832 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
833 // returns NULL on audio_processing().
834 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
835 if (audioproc) {
836 audioproc->SetExtraOptions(config);
837 }
838
kwiberg102c6a62015-10-30 02:47:38 -0700839 if (options.recording_sample_rate) {
840 LOG(LS_INFO) << "Recording sample rate is "
841 << *options.recording_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700842 if (adm()->SetRecordingSampleRate(*options.recording_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700843 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000844 }
845 }
846
kwiberg102c6a62015-10-30 02:47:38 -0700847 if (options.playout_sample_rate) {
848 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700849 if (adm()->SetPlayoutSampleRate(*options.playout_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700850 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000851 }
852 }
853
854 return true;
855}
856
solenberg246b8172015-12-08 09:50:23 -0800857void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800858 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800859#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800860 int in_id = kDefaultAudioDeviceId;
861 int out_id = kDefaultAudioDeviceId;
862 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
863 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000864
solenbergc1a1b352015-09-22 13:31:20 -0700865 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800866 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
867 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000868 ret = false;
869 }
solenberg246b8172015-12-08 09:50:23 -0800870 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
871 if (ap) {
872 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 }
874
solenberg246b8172015-12-08 09:50:23 -0800875 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
876 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877 ret = false;
878 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000880 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800881 LOG(LS_INFO) << "Set microphone to (id=" << in_id
882 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 }
kjellanderfcfc8042016-01-14 11:01:09 -0800884#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885}
886
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800888 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 unsigned int ulevel;
890 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
891 LOG_RTCERR1(GetSpeakerVolume, level);
892 return false;
893 }
894 *level = ulevel;
895 return true;
896}
897
898bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800899 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700900 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
902 LOG_RTCERR1(SetSpeakerVolume, level);
903 return false;
904 }
905 return true;
906}
907
908int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800909 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910 unsigned int ulevel;
911 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
912 static_cast<int>(ulevel) : -1;
913}
914
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800916 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return codecs_;
918}
919
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100920RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800921 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100922 RtpCapabilities capabilities;
923 capabilities.header_extensions.push_back(RtpHeaderExtension(
924 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
925 capabilities.header_extensions.push_back(
926 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
927 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800928 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
929 "Enabled") {
930 capabilities.header_extensions.push_back(RtpHeaderExtension(
931 kRtpTransportSequenceNumberHeaderExtension,
932 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
933 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100934 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935}
936
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800938 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 return voe_wrapper_->error();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
943 int length) {
solenberg566ef242015-11-06 15:34:49 -0800944 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000945 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000947 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000949 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000951 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000953 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954
solenberg72e29d22016-03-08 06:35:16 -0800955 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 if (length < 72) {
957 std::string msg(trace, length);
958 LOG(LS_ERROR) << "Malformed webrtc log message: ";
959 LOG_V(sev) << msg;
960 } else {
961 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +0200962 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 }
964}
965
solenberg63b34542015-09-29 06:06:31 -0700966void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800967 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
968 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 channels_.push_back(channel);
970}
971
solenberg63b34542015-09-29 06:06:31 -0700972void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800973 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -0700974 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -0800975 RTC_DCHECK(it != channels_.end());
976 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977}
978
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979// Adjusts the default AGC target level by the specified delta.
980// NB: If we start messing with other config fields, we'll want
981// to save the current webrtc::AgcConfig as well.
982bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -0800983 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 webrtc::AgcConfig config = default_agc_config_;
985 config.targetLeveldBOv -= delta;
986
987 LOG(LS_INFO) << "Adjusting AGC level from default -"
988 << default_agc_config_.targetLeveldBOv << "dB to -"
989 << config.targetLeveldBOv << "dB";
990
991 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
992 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
993 return false;
994 }
995 return true;
996}
997
ivocd66b44d2016-01-15 03:06:36 -0800998bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
999 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -08001000 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001001 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001002 if (!aec_dump_file_stream) {
1003 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001004 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001005 LOG(LS_WARNING) << "Could not close file.";
1006 return false;
1007 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001008 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001009 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1010 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001011 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001012 LOG_RTCERR0(StartDebugRecording);
1013 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001014 return false;
1015 }
1016 is_dumping_aec_ = true;
1017 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001018}
1019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001021 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 if (!is_dumping_aec_) {
1023 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001024 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1025 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001026 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027 } else {
1028 is_dumping_aec_ = true;
1029 }
1030 }
1031}
1032
1033void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001034 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 if (is_dumping_aec_) {
1036 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001037 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 webrtc::AudioProcessing::kNoError) {
1039 LOG_RTCERR0(StopDebugRecording);
1040 }
1041 is_dumping_aec_ = false;
1042 }
1043}
1044
ivoc112a3d82015-10-16 02:22:18 -07001045bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001046 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001047 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1048 if (event_log) {
1049 return event_log->StartLogging(file);
1050 }
1051 LOG_RTCERR0(StartRtcEventLog);
1052 return false;
ivoc112a3d82015-10-16 02:22:18 -07001053}
1054
1055void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001056 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001057 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1058 if (event_log) {
1059 event_log->StopLogging();
1060 return;
1061 }
1062 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001063}
1064
solenberg0a617e22015-10-20 15:49:38 -07001065int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001066 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001067 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001068}
1069
solenberg5b5129a2016-04-08 05:35:48 -07001070webrtc::AudioDeviceModule* WebRtcVoiceEngine::adm() {
1071 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1072 RTC_DCHECK(adm_);
1073 return adm_;
1074}
1075
solenbergc96df772015-10-21 13:01:53 -07001076class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001077 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001078 public:
skvlade0d46372016-04-07 22:59:22 -07001079 WebRtcAudioSendStream(int ch,
1080 webrtc::AudioTransport* voe_audio_transport,
1081 uint32_t ssrc,
1082 const std::string& c_name,
solenberg3a941542015-11-16 07:34:50 -08001083 const std::vector<webrtc::RtpExtension>& extensions,
1084 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001085 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001086 call_(call),
skvlade0d46372016-04-07 22:59:22 -07001087 config_(nullptr),
1088 rtp_parameters_(CreateRtpParametersWithOneEncoding()) {
solenberg85a04962015-10-27 03:35:21 -07001089 RTC_DCHECK_GE(ch, 0);
1090 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1091 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001092 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001093 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001094 config_.rtp.ssrc = ssrc;
1095 config_.rtp.c_name = c_name;
1096 config_.voe_channel_id = ch;
1097 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001098 }
solenberg3a941542015-11-16 07:34:50 -08001099
solenbergc96df772015-10-21 13:01:53 -07001100 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001101 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001102 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001103 call_->DestroyAudioSendStream(stream_);
1104 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001105
solenberg3a941542015-11-16 07:34:50 -08001106 void RecreateAudioSendStream(
1107 const std::vector<webrtc::RtpExtension>& extensions) {
1108 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1109 if (stream_) {
1110 call_->DestroyAudioSendStream(stream_);
1111 stream_ = nullptr;
1112 }
1113 config_.rtp.extensions = extensions;
1114 RTC_DCHECK(!stream_);
1115 stream_ = call_->CreateAudioSendStream(config_);
1116 RTC_CHECK(stream_);
solenberg6d6e7c52016-04-13 09:07:30 -07001117 UpdateSendState();
solenberg3a941542015-11-16 07:34:50 -08001118 }
1119
solenberg8842c3e2016-03-11 03:06:41 -08001120 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001121 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1122 RTC_DCHECK(stream_);
1123 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1124 }
1125
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001126 void SetSend(bool send) {
1127 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1128 send_ = send;
1129 UpdateSendState();
1130 }
1131
solenberg3a941542015-11-16 07:34:50 -08001132 webrtc::AudioSendStream::Stats GetStats() const {
1133 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1134 RTC_DCHECK(stream_);
1135 return stream_->GetStats();
1136 }
1137
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001138 // Starts the sending by setting ourselves as a sink to the AudioSource to
1139 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001140 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001141 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001142 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001143 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001144 RTC_DCHECK(source);
1145 if (source_) {
1146 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001147 return;
1148 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001149 source->SetSink(this);
1150 source_ = source;
1151 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001152 }
1153
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001154 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001155 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001156 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001157 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001158 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001159 if (source_) {
1160 source_->SetSink(nullptr);
1161 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001162 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001163 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001164 }
1165
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001166 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001167 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001168 void OnData(const void* audio_data,
1169 int bits_per_sample,
1170 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001171 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001172 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001173 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001174 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001175 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001176 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001177 audio_data,
1178 bits_per_sample,
1179 sample_rate,
1180 number_of_channels,
1181 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001182 }
1183
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001184 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001185 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001186 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001187 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001188 // Set |source_| to nullptr to make sure no more callback will get into
1189 // the source.
1190 source_ = nullptr;
1191 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001192 }
1193
1194 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001195 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001196 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001197 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001198 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001199
skvlade0d46372016-04-07 22:59:22 -07001200 const webrtc::RtpParameters& rtp_parameters() const {
1201 return rtp_parameters_;
1202 }
1203
1204 void set_rtp_parameters(const webrtc::RtpParameters& parameters) {
1205 RTC_CHECK_EQ(1UL, parameters.encodings.size());
1206 rtp_parameters_ = parameters;
1207 }
1208
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001209 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001210 void UpdateSendState() {
1211 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1212 RTC_DCHECK(stream_);
1213 if (send_ && source_ != nullptr) {
1214 stream_->Start();
1215 } else { // !send || source_ = nullptr
1216 stream_->Stop();
1217 }
1218 }
1219
solenberg566ef242015-11-06 15:34:49 -08001220 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001221 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001222 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1223 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001224 webrtc::AudioSendStream::Config config_;
1225 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1226 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001227 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001228
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001229 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001230 // PeerConnection will make sure invalidating the pointer before the object
1231 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001232 AudioSource* source_ = nullptr;
1233 bool send_ = false;
skvlade0d46372016-04-07 22:59:22 -07001234 webrtc::RtpParameters rtp_parameters_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001235
solenbergc96df772015-10-21 13:01:53 -07001236 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1237};
1238
1239class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1240 public:
stefanba4c0e42016-02-04 04:12:24 -08001241 WebRtcAudioReceiveStream(int ch,
1242 uint32_t remote_ssrc,
1243 uint32_t local_ssrc,
1244 bool use_transport_cc,
1245 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001246 const std::vector<webrtc::RtpExtension>& extensions,
1247 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001248 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001249 RTC_DCHECK_GE(ch, 0);
1250 RTC_DCHECK(call);
1251 config_.rtp.remote_ssrc = remote_ssrc;
1252 config_.rtp.local_ssrc = local_ssrc;
1253 config_.voe_channel_id = ch;
1254 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001255 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001256 }
solenbergc96df772015-10-21 13:01:53 -07001257
solenberg7add0582015-11-20 09:59:34 -08001258 ~WebRtcAudioReceiveStream() {
1259 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1260 call_->DestroyAudioReceiveStream(stream_);
1261 }
1262
1263 void RecreateAudioReceiveStream(
1264 const std::vector<webrtc::RtpExtension>& extensions) {
1265 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001266 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001267 }
stefanba4c0e42016-02-04 04:12:24 -08001268 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001269 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001270 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001271 }
1272
1273 webrtc::AudioReceiveStream::Stats GetStats() const {
1274 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1275 RTC_DCHECK(stream_);
1276 return stream_->GetStats();
1277 }
1278
1279 int channel() const {
1280 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1281 return config_.voe_channel_id;
1282 }
solenbergc96df772015-10-21 13:01:53 -07001283
kwiberg686a8ef2016-02-26 03:00:35 -08001284 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001285 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001286 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001287 }
1288
solenbergc96df772015-10-21 13:01:53 -07001289 private:
stefanba4c0e42016-02-04 04:12:24 -08001290 void RecreateAudioReceiveStream(
1291 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001292 const std::vector<webrtc::RtpExtension>& extensions) {
1293 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1294 if (stream_) {
1295 call_->DestroyAudioReceiveStream(stream_);
1296 stream_ = nullptr;
1297 }
1298 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001299 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001300 RTC_DCHECK(!stream_);
1301 stream_ = call_->CreateAudioReceiveStream(config_);
1302 RTC_CHECK(stream_);
1303 }
1304
1305 rtc::ThreadChecker worker_thread_checker_;
1306 webrtc::Call* call_ = nullptr;
1307 webrtc::AudioReceiveStream::Config config_;
1308 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1309 // configuration changes.
1310 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001311
1312 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001313};
1314
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001315WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001316 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001317 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001318 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001319 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001320 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001321 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001322 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001323 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324}
1325
1326WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001327 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001328 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001329 // TODO(solenberg): Should be able to delete the streams directly, without
1330 // going through RemoveNnStream(), once stream objects handle
1331 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001332 while (!send_streams_.empty()) {
1333 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001334 }
solenberg7add0582015-11-20 09:59:34 -08001335 while (!recv_streams_.empty()) {
1336 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 }
solenberg0a617e22015-10-20 15:49:38 -07001338 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339}
1340
nisse51542be2016-02-12 02:27:06 -08001341rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1342 return kAudioDscpValue;
1343}
1344
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001345bool WebRtcVoiceMediaChannel::SetSendParameters(
1346 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001347 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001348 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001349 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1350 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001351 // TODO(pthatcher): Refactor this to be more clean now that we have
1352 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001353
1354 if (!SetSendCodecs(params.codecs)) {
1355 return false;
1356 }
1357
solenberg7e4e01a2015-12-02 08:05:01 -08001358 if (!ValidateRtpExtensions(params.extensions)) {
1359 return false;
1360 }
1361 std::vector<webrtc::RtpExtension> filtered_extensions =
1362 FilterRtpExtensions(params.extensions,
1363 webrtc::RtpExtension::IsSupportedForAudio, true);
1364 if (send_rtp_extensions_ != filtered_extensions) {
1365 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001366 for (auto& it : send_streams_) {
1367 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1368 }
1369 }
1370
skvlade0d46372016-04-07 22:59:22 -07001371 if (!SetSendBitrate(params.max_bandwidth_bps)) {
solenberg3a941542015-11-16 07:34:50 -08001372 return false;
1373 }
1374 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001375}
1376
1377bool WebRtcVoiceMediaChannel::SetRecvParameters(
1378 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001379 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001380 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001381 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1382 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001383 // TODO(pthatcher): Refactor this to be more clean now that we have
1384 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001385
1386 if (!SetRecvCodecs(params.codecs)) {
1387 return false;
1388 }
1389
solenberg7e4e01a2015-12-02 08:05:01 -08001390 if (!ValidateRtpExtensions(params.extensions)) {
1391 return false;
1392 }
1393 std::vector<webrtc::RtpExtension> filtered_extensions =
1394 FilterRtpExtensions(params.extensions,
1395 webrtc::RtpExtension::IsSupportedForAudio, false);
1396 if (recv_rtp_extensions_ != filtered_extensions) {
1397 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001398 for (auto& it : recv_streams_) {
1399 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1400 }
1401 }
solenberg7add0582015-11-20 09:59:34 -08001402 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001403}
1404
skvlade0d46372016-04-07 22:59:22 -07001405webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpParameters(
1406 uint32_t ssrc) const {
1407 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1408 auto it = send_streams_.find(ssrc);
1409 if (it == send_streams_.end()) {
1410 LOG(LS_WARNING) << "Attempting to get RTP parameters for stream with ssrc "
1411 << ssrc << " which doesn't exist.";
1412 return webrtc::RtpParameters();
1413 }
1414
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001415 webrtc::RtpParameters rtp_params = it->second->rtp_parameters();
1416 // Need to add the common list of codecs to the send stream-specific
1417 // RTP parameters.
1418 for (const AudioCodec& codec : send_codecs_) {
1419 rtp_params.codecs.push_back(codec.ToCodecParameters());
1420 }
1421 return rtp_params;
skvlade0d46372016-04-07 22:59:22 -07001422}
1423
1424bool WebRtcVoiceMediaChannel::SetRtpParameters(
1425 uint32_t ssrc,
1426 const webrtc::RtpParameters& parameters) {
1427 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1428 if (!ValidateRtpParameters(parameters)) {
1429 return false;
1430 }
1431 auto it = send_streams_.find(ssrc);
1432 if (it == send_streams_.end()) {
1433 LOG(LS_WARNING) << "Attempting to set RTP parameters for stream with ssrc "
1434 << ssrc << " which doesn't exist.";
1435 return false;
1436 }
1437
1438 if (!SetChannelParameters(it->second->channel(), parameters)) {
1439 LOG(LS_WARNING) << "Failed to set RtpParameters.";
1440 return false;
1441 }
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001442 // Codecs are handled at the WebRtcVoiceMediaChannel level.
1443 webrtc::RtpParameters reduced_params = parameters;
1444 reduced_params.codecs.clear();
1445 it->second->set_rtp_parameters(reduced_params);
skvlade0d46372016-04-07 22:59:22 -07001446 return true;
1447}
1448
1449bool WebRtcVoiceMediaChannel::ValidateRtpParameters(
1450 const webrtc::RtpParameters& rtp_parameters) {
1451 if (rtp_parameters.encodings.size() != 1) {
1452 LOG(LS_ERROR)
1453 << "Attempted to set RtpParameters without exactly one encoding";
1454 return false;
1455 }
1456 return true;
1457}
1458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001460 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 LOG(LS_INFO) << "Setting voice channel options: "
1462 << options.ToString();
1463
1464 // We retain all of the existing options, and apply the given ones
1465 // on top. This means there is no way to "clear" options such that
1466 // they go back to the engine default.
1467 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001468 if (!engine()->ApplyOptions(options_)) {
1469 LOG(LS_WARNING) <<
1470 "Failed to apply engine options during channel SetOptions.";
1471 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 LOG(LS_INFO) << "Set voice channel options. Current options: "
1474 << options_.ToString();
1475 return true;
1476}
1477
1478bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1479 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001480 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001481
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001483 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001484
1485 if (!VerifyUniquePayloadTypes(codecs)) {
1486 LOG(LS_ERROR) << "Codec payload types overlap.";
1487 return false;
1488 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489
1490 std::vector<AudioCodec> new_codecs;
1491 // Find all new codecs. We allow adding new codecs but don't allow changing
1492 // the payload type of codecs that is already configured since we might
1493 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001494 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001496 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1497 if (old_codec.id != codec.id) {
1498 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 return false;
1500 }
1501 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001502 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503 }
1504 }
1505 if (new_codecs.empty()) {
1506 // There are no new codecs to configure. Already configured codecs are
1507 // never removed.
1508 return true;
1509 }
1510
1511 if (playout_) {
1512 // Receive codecs can not be changed while playing. So we temporarily
1513 // pause playout.
1514 PausePlayout();
1515 }
1516
solenberg26c8c912015-11-27 04:00:25 -08001517 bool result = true;
1518 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001519 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001520 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1521 LOG(LS_INFO) << ToString(codec);
1522 voe_codec.pltype = codec.id;
1523 for (const auto& ch : recv_streams_) {
1524 if (engine()->voe()->codec()->SetRecPayloadType(
1525 ch.second->channel(), voe_codec) == -1) {
1526 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1527 ToString(voe_codec));
1528 result = false;
1529 }
1530 }
1531 } else {
1532 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1533 result = false;
1534 break;
1535 }
1536 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001537 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538 recv_codecs_ = codecs;
1539 }
1540
1541 if (desired_playout_ && !playout_) {
1542 ResumePlayout();
1543 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001544 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545}
1546
solenberg72e29d22016-03-08 06:35:16 -08001547// Utility function called from SetSendParameters() to extract current send
1548// codec settings from the given list of codecs (originally from SDP). Both send
1549// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001550bool WebRtcVoiceMediaChannel::SetSendCodecs(
1551 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001552 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001553 // TODO(solenberg): Validate input - that payload types don't overlap, are
1554 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001555 // redundant codecs etc - the same way it is done for
1556 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001557
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001558 // Find the DTMF telephone event "codec" payload type.
1559 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001560 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001561 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001562 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1563 return false;
1564 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001565 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1566 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001567 }
1568 }
1569
solenberg72e29d22016-03-08 06:35:16 -08001570 // Scan through the list to figure out the codec to use for sending, along
1571 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1572 // parameters.
1573 {
1574 SendCodecSpec send_codec_spec;
1575 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1576
1577 // Find send codec (the first non-telephone-event/CN codec).
1578 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1579 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1580 if (!codec) {
1581 LOG(LS_WARNING) << "Received empty list of codecs.";
1582 return false;
1583 }
1584
1585 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1586
1587 // This condition is apparently here because Opus does not support RED and
1588 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1589 // such limitations.
1590 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1591 if (send_codec_spec.red_payload_type == -1) {
1592 send_codec_spec.nack_enabled = HasNack(*codec);
1593 // For Opus as the send codec, we are to determine inband FEC, maximum
1594 // playback rate, and opus internal dtx.
1595 if (IsCodec(*codec, kOpusCodecName)) {
1596 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1597 &send_codec_spec.enable_codec_fec,
1598 &send_codec_spec.opus_max_playback_rate,
1599 &send_codec_spec.enable_opus_dtx);
1600 }
1601
1602 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1603 int ptime_ms = 0;
1604 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1605 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1606 &send_codec_spec.codec_inst, ptime_ms)) {
1607 LOG(LS_WARNING) << "Failed to set packet size for codec "
1608 << send_codec_spec.codec_inst.plname;
1609 return false;
1610 }
1611 }
1612 }
1613
1614 // Loop through the codecs list again to find the CN codec.
1615 // TODO(solenberg): Break out into a separate function?
1616 for (const AudioCodec& codec : codecs) {
1617 // Ignore codecs we don't know about. The negotiation step should prevent
1618 // this, but double-check to be sure.
1619 webrtc::CodecInst voe_codec = {0};
1620 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1621 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1622 continue;
1623 }
1624
1625 if (IsCodec(codec, kCnCodecName)) {
1626 // Turn voice activity detection/comfort noise on if supported.
1627 // Set the wideband CN payload type appropriately.
1628 // (narrowband always uses the static payload type 13).
1629 int cng_plfreq = -1;
1630 switch (codec.clockrate) {
1631 case 8000:
1632 case 16000:
1633 case 32000:
1634 cng_plfreq = codec.clockrate;
1635 break;
1636 default:
1637 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1638 << " not supported.";
1639 continue;
1640 }
1641 send_codec_spec.cng_payload_type = codec.id;
1642 send_codec_spec.cng_plfreq = cng_plfreq;
1643 break;
1644 }
1645 }
1646
1647 // Latch in the new state.
1648 send_codec_spec_ = std::move(send_codec_spec);
1649 }
1650
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001651 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001652 for (const auto& ch : send_streams_) {
skvlade0d46372016-04-07 22:59:22 -07001653 if (!SetSendCodecs(ch.second->channel(), ch.second->rtp_parameters())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001654 return false;
1655 }
1656 }
1657
solenberg72e29d22016-03-08 06:35:16 -08001658 // Set nack status on receive channels.
1659 if (!send_streams_.empty()) {
1660 for (const auto& kv : recv_streams_) {
1661 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1662 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001663 }
solenberg0a617e22015-10-20 15:49:38 -07001664
stefanba4c0e42016-02-04 04:12:24 -08001665 // Check if the transport cc feedback has changed on the preferred send codec,
1666 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001667 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1668 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1669 "codec has changed.";
1670 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1671 for (auto& kv : recv_streams_) {
1672 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1673 }
1674 }
1675
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001676 send_codecs_ = codecs;
solenberg72e29d22016-03-08 06:35:16 -08001677 return true;
1678}
1679
1680// Apply current codec settings to a single voe::Channel used for sending.
skvlade0d46372016-04-07 22:59:22 -07001681bool WebRtcVoiceMediaChannel::SetSendCodecs(
1682 int channel,
1683 const webrtc::RtpParameters& rtp_parameters) {
solenberg72e29d22016-03-08 06:35:16 -08001684 // Disable VAD, FEC, and RED unless we know the other side wants them.
1685 engine()->voe()->codec()->SetVADStatus(channel, false);
1686 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1687 engine()->voe()->rtp()->SetREDStatus(channel, false);
1688 engine()->voe()->codec()->SetFECStatus(channel, false);
1689
1690 if (send_codec_spec_.red_payload_type != -1) {
1691 // Enable redundant encoding of the specified codec. Treat any
1692 // failure as a fatal internal error.
1693 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1694 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1695 send_codec_spec_.red_payload_type) == -1) {
1696 LOG_RTCERR3(SetREDStatus, channel, true,
1697 send_codec_spec_.red_payload_type);
1698 return false;
1699 }
1700 }
1701
1702 SetNack(channel, send_codec_spec_.nack_enabled);
1703
1704 // Set the codec immediately, since SetVADStatus() depends on whether
1705 // the current codec is mono or stereo.
1706 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1707 return false;
1708 }
1709
1710 // FEC should be enabled after SetSendCodec.
1711 if (send_codec_spec_.enable_codec_fec) {
1712 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1713 << channel;
1714 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1715 // Enable codec internal FEC. Treat any failure as fatal internal error.
1716 LOG_RTCERR2(SetFECStatus, channel, true);
1717 return false;
1718 }
1719 }
1720
1721 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1722 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1723 // send codec has to be Opus.
1724
1725 // Set Opus internal DTX.
1726 LOG(LS_INFO) << "Attempt to "
1727 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1728 << " Opus DTX on channel "
1729 << channel;
1730 if (engine()->voe()->codec()->SetOpusDtx(channel,
1731 send_codec_spec_.enable_opus_dtx)) {
1732 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1733 return false;
1734 }
1735
1736 // If opus_max_playback_rate <= 0, the default maximum playback rate
1737 // (48 kHz) will be used.
1738 if (send_codec_spec_.opus_max_playback_rate > 0) {
1739 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1740 << send_codec_spec_.opus_max_playback_rate
1741 << " Hz on channel "
1742 << channel;
1743 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1744 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1745 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1746 send_codec_spec_.opus_max_playback_rate);
1747 return false;
stefanba4c0e42016-02-04 04:12:24 -08001748 }
1749 }
1750 }
skvlade0d46372016-04-07 22:59:22 -07001751 // TODO(solenberg): SetSendBitrate() yields another call to SetSendCodec().
1752 // Check if it is possible to fuse with the previous call in this function.
1753 SetChannelParameters(channel, rtp_parameters);
solenberg72e29d22016-03-08 06:35:16 -08001754
1755 // Set the CN payloadtype and the VAD status.
1756 if (send_codec_spec_.cng_payload_type != -1) {
1757 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1758 if (send_codec_spec_.cng_plfreq != 8000) {
1759 webrtc::PayloadFrequencies cn_freq;
1760 switch (send_codec_spec_.cng_plfreq) {
1761 case 16000:
1762 cn_freq = webrtc::kFreq16000Hz;
1763 break;
1764 case 32000:
1765 cn_freq = webrtc::kFreq32000Hz;
1766 break;
1767 default:
1768 RTC_NOTREACHED();
1769 return false;
1770 }
1771 if (engine()->voe()->codec()->SetSendCNPayloadType(
1772 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1773 LOG_RTCERR3(SetSendCNPayloadType, channel,
1774 send_codec_spec_.cng_payload_type, cn_freq);
1775 // TODO(ajm): This failure condition will be removed from VoE.
1776 // Restore the return here when we update to a new enough webrtc.
1777 //
1778 // Not returning false because the SetSendCNPayloadType will fail if
1779 // the channel is already sending.
1780 // This can happen if the remote description is applied twice, for
1781 // example in the case of ROAP on top of JSEP, where both side will
1782 // send the offer.
1783 }
1784 }
1785
1786 // Only turn on VAD if we have a CN payload type that matches the
1787 // clockrate for the codec we are going to use.
1788 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1789 send_codec_spec_.codec_inst.channels == 1) {
1790 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1791 // interaction between VAD and Opus FEC.
1792 LOG(LS_INFO) << "Enabling VAD";
1793 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1794 LOG_RTCERR2(SetVADStatus, channel, true);
1795 return false;
1796 }
1797 }
1798 }
solenberg0a617e22015-10-20 15:49:38 -07001799 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001800}
1801
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001802void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001804 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1806 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001807 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001808 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1809 }
1810}
1811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001813 int channel, const webrtc::CodecInst& send_codec) {
1814 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1815 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1816
solenberg72e29d22016-03-08 06:35:16 -08001817 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001818 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1819 (send_codec == current_codec)) {
1820 // Codec is already configured, we can return without setting it again.
1821 return true;
1822 }
1823
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001824 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1825 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 return false;
1827 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 return true;
1829}
1830
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1832 desired_playout_ = playout;
1833 return ChangePlayout(desired_playout_);
1834}
1835
1836bool WebRtcVoiceMediaChannel::PausePlayout() {
1837 return ChangePlayout(false);
1838}
1839
1840bool WebRtcVoiceMediaChannel::ResumePlayout() {
1841 return ChangePlayout(desired_playout_);
1842}
1843
1844bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001845 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001846 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 if (playout_ == playout) {
1848 return true;
1849 }
1850
solenberg7add0582015-11-20 09:59:34 -08001851 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001852 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001853 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001854 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001855 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 }
1857 }
solenberg1ac56142015-10-13 03:58:19 -07001858 playout_ = playout;
1859 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860}
1861
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001862void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001863 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001865 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866 }
1867
solenbergd53a3f92016-04-14 13:56:37 -07001868 // Apply channel specific options, and initialize the ADM for recording (this
1869 // may take time on some platforms, e.g. Android).
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001870 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001871 engine()->ApplyOptions(options_);
solenbergd53a3f92016-04-14 13:56:37 -07001872
1873 // InitRecording() may return an error if the ADM is already recording.
1874 if (!engine()->adm()->RecordingIsInitialized() &&
1875 !engine()->adm()->Recording()) {
1876 if (engine()->adm()->InitRecording() != 0) {
1877 LOG(LS_WARNING) << "Failed to initialize recording";
1878 }
1879 }
solenberg63b34542015-09-29 06:06:31 -07001880 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001882 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001883 for (auto& kv : send_streams_) {
1884 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888}
1889
Peter Boström0c4e06b2015-10-07 12:23:21 +02001890bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1891 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001892 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001893 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001894 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001895 // TODO(solenberg): The state change should be fully rolled back if any one of
1896 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001897 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001898 return false;
1899 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001900 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001901 return false;
1902 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001903 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001904 return SetOptions(*options);
1905 }
1906 return true;
1907}
1908
solenberg0a617e22015-10-20 15:49:38 -07001909int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1910 int id = engine()->CreateVoEChannel();
1911 if (id == -1) {
1912 LOG_RTCERR0(CreateVoEChannel);
1913 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001914 }
solenberg0a617e22015-10-20 15:49:38 -07001915 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1916 LOG_RTCERR2(RegisterExternalTransport, id, this);
1917 engine()->voe()->base()->DeleteChannel(id);
1918 return -1;
1919 }
1920 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001921}
1922
solenberg7add0582015-11-20 09:59:34 -08001923bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001924 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1925 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1926 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001927 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1928 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 return false;
1930 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001931 return true;
1932}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001933
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001934bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001935 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001936 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001937 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1938
1939 uint32_t ssrc = sp.first_ssrc();
1940 RTC_DCHECK(0 != ssrc);
1941
1942 if (GetSendChannelId(ssrc) != -1) {
1943 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001944 return false;
1945 }
1946
solenberg0a617e22015-10-20 15:49:38 -07001947 // Create a new channel for sending audio data.
1948 int channel = CreateVoEChannel();
1949 if (channel == -1) {
1950 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001951 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001952
solenbergc96df772015-10-21 13:01:53 -07001953 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001954 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001955 webrtc::AudioTransport* audio_transport =
1956 engine()->voe()->base()->audio_transport();
skvlade0d46372016-04-07 22:59:22 -07001957 WebRtcAudioSendStream* stream = new WebRtcAudioSendStream(
1958 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_);
1959 send_streams_.insert(std::make_pair(ssrc, stream));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001960
solenberg0a617e22015-10-20 15:49:38 -07001961 // Set the current codecs to be used for the new channel. We need to do this
1962 // after adding the channel to send_channels_, because of how max bitrate is
1963 // currently being configured by SetSendCodec().
skvlade0d46372016-04-07 22:59:22 -07001964 if (HasSendCodec() && !SetSendCodecs(channel, stream->rtp_parameters())) {
solenberg0a617e22015-10-20 15:49:38 -07001965 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001966 return false;
1967 }
1968
1969 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001970 // the first send channel make sure that all the receive channels are updated
1971 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001972 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001973 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001974 for (const auto& stream : recv_streams_) {
1975 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001976 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001977 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001978 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001979 }
solenberg0a617e22015-10-20 15:49:38 -07001980 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1981 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1982 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001983 }
1984 }
1985
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001986 send_streams_[ssrc]->SetSend(send_);
1987 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001988}
1989
Peter Boström0c4e06b2015-10-07 12:23:21 +02001990bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001991 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001992 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001993 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1994
solenbergc96df772015-10-21 13:01:53 -07001995 auto it = send_streams_.find(ssrc);
1996 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001997 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1998 << " which doesn't exist.";
1999 return false;
2000 }
2001
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002002 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002003
solenberg7add0582015-11-20 09:59:34 -08002004 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002005 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07002006 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2007 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08002008 delete it->second;
2009 send_streams_.erase(it);
2010 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07002011 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002012 }
solenbergc96df772015-10-21 13:01:53 -07002013 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002014 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07002015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016 return true;
2017}
2018
2019bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002020 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002021 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002022 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2023
solenberg0b675462015-10-09 01:37:09 -07002024 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002025 return false;
2026 }
2027
solenberg7add0582015-11-20 09:59:34 -08002028 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002029 if (ssrc == 0) {
2030 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2031 return false;
2032 }
2033
solenberg1ac56142015-10-13 03:58:19 -07002034 // Remove the default receive stream if one had been created with this ssrc;
2035 // we'll recreate it then.
2036 if (IsDefaultRecvStream(ssrc)) {
2037 RemoveRecvStream(ssrc);
2038 }
solenberg0b675462015-10-09 01:37:09 -07002039
solenberg7add0582015-11-20 09:59:34 -08002040 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002041 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 return false;
2043 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002044
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002046 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 return false;
2049 }
Minyue2013aec2015-05-13 14:14:42 +02002050
solenberg1ac56142015-10-13 03:58:19 -07002051 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002052 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2053 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2054 voe_codec.pltype = -1;
2055 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2056 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2057 DeleteVoEChannel(channel);
2058 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002059 }
2060 }
2061
solenberg1ac56142015-10-13 03:58:19 -07002062 // Only enable those configured for this channel.
2063 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002064 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002065 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002066 voe_codec.pltype = codec.id;
2067 if (engine()->voe()->codec()->SetRecPayloadType(
2068 channel, voe_codec) == -1) {
2069 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002070 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002071 return false;
2072 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002073 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002074 }
solenberg8fb30c32015-10-13 03:06:58 -07002075
solenberg7add0582015-11-20 09:59:34 -08002076 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2077 if (send_channel != -1) {
2078 // Associate receive channel with first send channel (so the receive channel
2079 // can obtain RTT from the send channel)
2080 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2081 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2082 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002083 }
2084
stefanba4c0e42016-02-04 04:12:24 -08002085 recv_streams_.insert(std::make_pair(
2086 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002087 recv_transport_cc_enabled_,
2088 sp.sync_label, recv_rtp_extensions_,
2089 call_)));
solenberg7add0582015-11-20 09:59:34 -08002090
solenberg72e29d22016-03-08 06:35:16 -08002091 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002092 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002093
solenberg1ac56142015-10-13 03:58:19 -07002094 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095}
2096
Peter Boström0c4e06b2015-10-07 12:23:21 +02002097bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002098 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002099 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002100 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2101
solenberg7add0582015-11-20 09:59:34 -08002102 const auto it = recv_streams_.find(ssrc);
2103 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002104 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2105 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002106 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002107 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108
solenberg1ac56142015-10-13 03:58:19 -07002109 // Deregister default channel, if that's the one being destroyed.
2110 if (IsDefaultRecvStream(ssrc)) {
2111 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002113
solenberg7add0582015-11-20 09:59:34 -08002114 const int channel = it->second->channel();
2115
2116 // Clean up and delete the receive stream+channel.
2117 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002118 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002119 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002120 delete it->second;
2121 recv_streams_.erase(it);
2122 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123}
2124
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002125bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2126 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002127 auto it = send_streams_.find(ssrc);
2128 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002129 if (source) {
2130 // Return an error if trying to set a valid source with an invalid ssrc.
2131 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002132 return false;
2133 }
2134
2135 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002136 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002137 }
2138
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002139 if (source) {
2140 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002141 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002142 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002143 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002144
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 return true;
2146}
2147
2148bool WebRtcVoiceMediaChannel::GetActiveStreams(
2149 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002150 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002152 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002153 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002155 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002156 }
2157 }
2158 return true;
2159}
2160
2161int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002162 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002163 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002164 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002165 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 }
2167 return highest;
2168}
2169
2170int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2171 int ret;
2172 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2173 // In case of error, log the info and continue
2174 LOG_RTCERR0(TimeSinceLastTyping);
2175 ret = -1;
2176 } else {
2177 ret *= 1000; // We return ms, webrtc returns seconds.
2178 }
2179 return ret;
2180}
2181
2182void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2183 int cost_per_typing, int reporting_threshold, int penalty_decay,
2184 int type_event_delay) {
2185 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2186 time_window, cost_per_typing,
2187 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2188 // In case of error, log the info and continue
2189 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2190 cost_per_typing, reporting_threshold, penalty_decay,
2191 type_event_delay);
2192 }
2193}
2194
solenberg4bac9c52015-10-09 02:32:53 -07002195bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002196 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002197 if (ssrc == 0) {
2198 default_recv_volume_ = volume;
2199 if (default_recv_ssrc_ == -1) {
2200 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 }
solenberg1ac56142015-10-13 03:58:19 -07002202 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2203 }
2204 int ch_id = GetReceiveChannelId(ssrc);
2205 if (ch_id < 0) {
2206 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2207 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208 }
2209
solenberg1ac56142015-10-13 03:58:19 -07002210 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2211 volume)) {
2212 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2213 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 }
solenberg1ac56142015-10-13 03:58:19 -07002215 LOG(LS_INFO) << "SetOutputVolume to " << volume
2216 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 return true;
2218}
2219
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002221 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002222}
2223
solenberg1d63dd02015-12-02 12:35:09 -08002224bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2225 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002226 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002227 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2228 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 return false;
2230 }
2231
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002232 // Figure out which WebRtcAudioSendStream to send the event on.
2233 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2234 if (it == send_streams_.end()) {
2235 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002236 return false;
2237 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002238 if (event < kMinTelephoneEventCode ||
2239 event > kMaxTelephoneEventCode) {
2240 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002241 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002243 if (duration < kMinTelephoneEventDuration ||
2244 duration > kMaxTelephoneEventDuration) {
2245 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2246 return false;
2247 }
2248 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249}
2250
wu@webrtc.orga9890802013-12-13 00:21:03 +00002251void WebRtcVoiceMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002252 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002253 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002254
solenberg1ac56142015-10-13 03:58:19 -07002255 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002256 if (!GetRtpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg1ac56142015-10-13 03:58:19 -07002257 return;
2258 }
2259
solenberg7e63ef02015-11-20 00:19:43 -08002260 // If we don't have a default channel, and the SSRC is unknown, create a
2261 // default channel.
2262 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002263 StreamParams sp;
2264 sp.ssrcs.push_back(ssrc);
2265 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2266 if (!AddRecvStream(sp)) {
2267 LOG(LS_WARNING) << "Could not create default receive stream.";
2268 return;
2269 }
2270 default_recv_ssrc_ = ssrc;
2271 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002272 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002273 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002274 new ProxySink(default_sink_.get()));
2275 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2276 }
solenberg1ac56142015-10-13 03:58:19 -07002277 }
2278
2279 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002280 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2281 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002282 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2283 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002284 packet->cdata(), packet->size(), webrtc_packet_time);
solenberg1ac56142015-10-13 03:58:19 -07002285 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002286 // If the SSRC is unknown here, route it to the default channel, if we have
2287 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2288 if (default_recv_ssrc_ == -1) {
2289 return;
2290 } else {
2291 ssrc = default_recv_ssrc_;
2292 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293 }
2294
solenberg1ac56142015-10-13 03:58:19 -07002295 // Find the channel to send this packet to. It must exist since webrtc::Call
2296 // was able to demux the packet.
2297 int channel = GetReceiveChannelId(ssrc);
2298 RTC_DCHECK(channel != -1);
2299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002301 engine()->voe()->network()->ReceivedRTPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002302 channel, packet->cdata(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002303}
2304
wu@webrtc.orga9890802013-12-13 00:21:03 +00002305void WebRtcVoiceMediaChannel::OnRtcpReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002306 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002307 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002308
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002309 // Forward packet to Call as well.
2310 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2311 packet_time.not_before);
2312 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002313 packet->cdata(), packet->size(), webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002314
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002315 // Sending channels need all RTCP packets with feedback information.
2316 // Even sender reports can contain attached report blocks.
2317 // Receiving channels need sender reports in order to create
2318 // correct receiver reports.
2319 int type = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002320 if (!GetRtcpType(packet->cdata(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002321 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2322 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 }
2324
solenberg0b675462015-10-09 01:37:09 -07002325 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002326 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002327 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002328 if (!GetRtcpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg0b675462015-10-09 01:37:09 -07002329 return;
2330 }
2331 int recv_channel_id = GetReceiveChannelId(ssrc);
2332 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002333 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002334 recv_channel_id, packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002335 }
2336 }
2337
2338 // SR may continue RR and any RR entry may correspond to any one of the send
2339 // channels. So all RTCP packets must be forwarded all send channels. VoE
2340 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002341 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002342 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002343 ch.second->channel(), packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345}
2346
Honghai Zhangcc411c02016-03-29 17:27:21 -07002347void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2348 const std::string& transport_name,
Honghai Zhang0e533ef2016-04-19 15:41:36 -07002349 const rtc::NetworkRoute& network_route) {
2350 call_->OnNetworkRouteChanged(transport_name, network_route);
Honghai Zhangcc411c02016-03-29 17:27:21 -07002351}
2352
Peter Boström0c4e06b2015-10-07 12:23:21 +02002353bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002354 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002355 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002356 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002357 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2358 return false;
2359 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002360 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2361 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002362 return false;
2363 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002364 // We set the AGC to mute state only when all the channels are muted.
2365 // This implementation is not ideal, instead we should signal the AGC when
2366 // the mic channel is muted/unmuted. We can't do it today because there
2367 // is no good way to know which stream is mapping to the mic channel.
2368 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002369 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002370 if (!all_muted) {
2371 break;
2372 }
2373 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002374 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002375 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002376 return false;
2377 }
2378 }
2379
2380 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002381 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002382 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002383 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 return true;
2385}
2386
skvlade0d46372016-04-07 22:59:22 -07002387bool WebRtcVoiceMediaChannel::SetSendBitrate(int bps) {
2388 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrate.";
2389 send_bitrate_bps_ = bps;
2390
2391 for (const auto& kv : send_streams_) {
2392 if (!SetChannelParameters(kv.second->channel(),
2393 kv.second->rtp_parameters())) {
2394 return false;
2395 }
2396 }
2397 return true;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002398}
2399
skvlade0d46372016-04-07 22:59:22 -07002400bool WebRtcVoiceMediaChannel::SetChannelParameters(
2401 int channel,
2402 const webrtc::RtpParameters& parameters) {
2403 RTC_CHECK_EQ(1UL, parameters.encodings.size());
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07002404 // TODO(deadbeef): Handle setting parameters with a list of codecs in a
2405 // different order (which should change the send codec).
skvlade0d46372016-04-07 22:59:22 -07002406 return SetSendBitrate(
2407 channel,
2408 MinPositive(send_bitrate_bps_, parameters.encodings[0].max_bitrate_bps));
2409}
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002410
skvlade0d46372016-04-07 22:59:22 -07002411bool WebRtcVoiceMediaChannel::SetSendBitrate(int channel, int bps) {
2412 // Bitrate is auto by default.
2413 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2414 // SetMaxSendBandwith(0), the second call removes the previous limit.
2415 if (bps <= 0)
2416 return true;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002417
solenberg72e29d22016-03-08 06:35:16 -08002418 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002419 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002420 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002421 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 }
2423
solenberg72e29d22016-03-08 06:35:16 -08002424 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002425 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426
2427 if (is_multi_rate) {
2428 // If codec is multi-rate then just set the bitrate.
2429 codec.rate = bps;
skvlade0d46372016-04-07 22:59:22 -07002430 if (!SetSendCodec(channel, codec)) {
2431 LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate "
2432 << bps << " bps.";
2433 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 }
2435 return true;
2436 } else {
2437 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2438 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2439 // fixed bitrate then ignore.
2440 if (bps < codec.rate) {
2441 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2442 << " to bitrate " << bps << " bps"
2443 << ", requires at least " << codec.rate << " bps.";
2444 return false;
2445 }
2446 return true;
2447 }
2448}
2449
skvlad7a43d252016-03-22 15:32:27 -07002450void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2451 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2452 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2453 call_->SignalChannelNetworkState(
2454 webrtc::MediaType::AUDIO,
2455 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2456}
2457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002459 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002460 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002461 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002462
solenberg85a04962015-10-27 03:35:21 -07002463 // Get SSRC and stats for each sender.
2464 RTC_DCHECK(info->senders.size() == 0);
2465 for (const auto& stream : send_streams_) {
2466 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002467 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002468 sinfo.add_ssrc(stats.local_ssrc);
2469 sinfo.bytes_sent = stats.bytes_sent;
2470 sinfo.packets_sent = stats.packets_sent;
2471 sinfo.packets_lost = stats.packets_lost;
2472 sinfo.fraction_lost = stats.fraction_lost;
2473 sinfo.codec_name = stats.codec_name;
2474 sinfo.ext_seqnum = stats.ext_seqnum;
2475 sinfo.jitter_ms = stats.jitter_ms;
2476 sinfo.rtt_ms = stats.rtt_ms;
2477 sinfo.audio_level = stats.audio_level;
2478 sinfo.aec_quality_min = stats.aec_quality_min;
2479 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2480 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2481 sinfo.echo_return_loss = stats.echo_return_loss;
2482 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002483 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002484 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002485 }
2486
solenberg85a04962015-10-27 03:35:21 -07002487 // Get SSRC and stats for each receiver.
2488 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002489 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002490 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2491 VoiceReceiverInfo rinfo;
2492 rinfo.add_ssrc(stats.remote_ssrc);
2493 rinfo.bytes_rcvd = stats.bytes_rcvd;
2494 rinfo.packets_rcvd = stats.packets_rcvd;
2495 rinfo.packets_lost = stats.packets_lost;
2496 rinfo.fraction_lost = stats.fraction_lost;
2497 rinfo.codec_name = stats.codec_name;
2498 rinfo.ext_seqnum = stats.ext_seqnum;
2499 rinfo.jitter_ms = stats.jitter_ms;
2500 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2501 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2502 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2503 rinfo.audio_level = stats.audio_level;
2504 rinfo.expand_rate = stats.expand_rate;
2505 rinfo.speech_expand_rate = stats.speech_expand_rate;
2506 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2507 rinfo.accelerate_rate = stats.accelerate_rate;
2508 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2509 rinfo.decoding_calls_to_silence_generator =
2510 stats.decoding_calls_to_silence_generator;
2511 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2512 rinfo.decoding_normal = stats.decoding_normal;
2513 rinfo.decoding_plc = stats.decoding_plc;
2514 rinfo.decoding_cng = stats.decoding_cng;
2515 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2516 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2517 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 }
2519
2520 return true;
2521}
2522
Tommif888bb52015-12-12 01:37:01 +01002523void WebRtcVoiceMediaChannel::SetRawAudioSink(
2524 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002525 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002526 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002527 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2528 << " " << (sink ? "(ptr)" : "NULL");
2529 if (ssrc == 0) {
2530 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002531 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002532 sink ? new ProxySink(sink.get()) : nullptr);
2533 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2534 }
2535 default_sink_ = std::move(sink);
2536 return;
2537 }
Tommif888bb52015-12-12 01:37:01 +01002538 const auto it = recv_streams_.find(ssrc);
2539 if (it == recv_streams_.end()) {
2540 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2541 return;
2542 }
deadbeef2d110be2016-01-13 12:00:26 -08002543 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002544}
2545
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002546int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002547 unsigned int ulevel = 0;
2548 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2550}
2551
Peter Boström0c4e06b2015-10-07 12:23:21 +02002552int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002553 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002554 const auto it = recv_streams_.find(ssrc);
2555 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002556 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002557 }
solenberg1ac56142015-10-13 03:58:19 -07002558 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559}
2560
Peter Boström0c4e06b2015-10-07 12:23:21 +02002561int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002562 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002563 const auto it = send_streams_.find(ssrc);
2564 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002565 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002566 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002567 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002568}
2569
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2571 if (playout) {
2572 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2573 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2574 LOG_RTCERR1(StartPlayout, channel);
2575 return false;
2576 }
2577 } else {
2578 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2579 engine()->voe()->base()->StopPlayout(channel);
2580 }
2581 return true;
2582}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583} // namespace cricket
2584
2585#endif // HAVE_WEBRTC_VOICE