blob: 8561aa2dc4fbcf2c238bef44cee9bcc838334d58 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellander1afca732016-02-07 20:46:45 -08002 * Copyright (c) 2004 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellander1afca732016-02-07 20:46:45 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
henrike@webrtc.org28e20752013-07-10 00:45:36 +000011#ifdef HAVE_WEBRTC_VOICE
12
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010013#include "webrtc/media/engine/webrtcvoiceengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000014
15#include <algorithm>
16#include <cstdio>
17#include <string>
18#include <vector>
19
kjellander@webrtc.org7ffeab52016-02-26 22:46:09 +010020#include "webrtc/audio_sink.h"
tfarina5237aaf2015-11-10 23:44:30 -080021#include "webrtc/base/arraysize.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000022#include "webrtc/base/base64.h"
23#include "webrtc/base/byteorder.h"
24#include "webrtc/base/common.h"
25#include "webrtc/base/helpers.h"
26#include "webrtc/base/logging.h"
27#include "webrtc/base/stringencode.h"
28#include "webrtc/base/stringutils.h"
Peter Boströmca8b4042016-03-08 14:24:13 -080029#include "webrtc/base/trace_event.h"
ivoc112a3d82015-10-16 02:22:18 -070030#include "webrtc/call/rtc_event_log.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000031#include "webrtc/common.h"
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -080032#include "webrtc/media/base/audiosource.h"
kjellanderf4752772016-03-02 05:42:30 -080033#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080034#include "webrtc/media/base/streamparams.h"
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010035#include "webrtc/media/engine/webrtcmediaengine.h"
36#include "webrtc/media/engine/webrtcvoe.h"
solenberg26c8c912015-11-27 04:00:25 -080037#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000038#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010039#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080040#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070043namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
solenbergbd138382015-11-20 16:08:07 -080045const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
46 webrtc::kTraceWarning | webrtc::kTraceError |
47 webrtc::kTraceCritical;
48const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
49 webrtc::kTraceInfo;
50
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051// On Windows Vista and newer, Microsoft introduced the concept of "Default
52// Communications Device". This means that there are two types of default
53// devices (old Wave Audio style default and Default Communications Device).
54//
55// On Windows systems which only support Wave Audio style default, uses either
56// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070058const int kDefaultAudioDeviceId = -1;
solenberg8ad582d2016-03-16 09:34:56 -070059#elif !defined(WEBRTC_IOS)
solenbergd97ec302015-10-07 01:40:33 -070060const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061#endif
62
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063// Parameter used for NACK.
64// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070065const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000066
67// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000068// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000069
70// Recommended bitrates:
71// 8-12 kb/s for NB speech,
72// 16-20 kb/s for WB speech,
73// 28-40 kb/s for FB speech,
74// 48-64 kb/s for FB mono music, and
75// 64-128 kb/s for FB stereo music.
76// The current implementation applies the following values to mono signals,
77// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070078const int kOpusBitrateNb = 12000;
79const int kOpusBitrateWb = 20000;
80const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000081
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000082// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -070083const int kOpusMinBitrate = 6000;
84const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000085
wu@webrtc.orgde305012013-10-31 15:40:38 +000086// Default audio dscp value.
87// See http://tools.ietf.org/html/rfc2474 for details.
88// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -070089const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000090
Fredrik Solenbergb5727682015-12-04 15:22:19 +010091// Constants from voice_engine_defines.h.
92const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
93const int kMaxTelephoneEventCode = 255;
94const int kMinTelephoneEventDuration = 100;
95const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
96
solenberg31642aa2016-03-14 08:00:37 -070097const int kMinPayloadType = 0;
98const int kMaxPayloadType = 127;
99
deadbeef884f5852016-01-15 09:20:04 -0800100class ProxySink : public webrtc::AudioSinkInterface {
101 public:
102 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
103
104 void OnData(const Data& audio) override { sink_->OnData(audio); }
105
106 private:
107 webrtc::AudioSinkInterface* sink_;
108};
109
solenberg0b675462015-10-09 01:37:09 -0700110bool ValidateStreamParams(const StreamParams& sp) {
111 if (sp.ssrcs.empty()) {
112 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
113 return false;
114 }
115 if (sp.ssrcs.size() > 1) {
116 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
117 return false;
118 }
119 return true;
120}
121
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700123std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124 std::stringstream ss;
125 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
126 << " (" << codec.id << ")";
127 return ss.str();
128}
Minyue Li7100dcd2015-03-27 05:05:59 +0100129
solenbergd97ec302015-10-07 01:40:33 -0700130std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 std::stringstream ss;
132 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
133 << " (" << codec.pltype << ")";
134 return ss.str();
135}
136
solenbergd97ec302015-10-07 01:40:33 -0700137bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100138 return (_stricmp(codec.name.c_str(), ref_name) == 0);
139}
140
solenbergd97ec302015-10-07 01:40:33 -0700141bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100142 return (_stricmp(codec.plname, ref_name) == 0);
143}
144
solenbergd97ec302015-10-07 01:40:33 -0700145bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800146 const AudioCodec& codec,
147 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200148 for (const AudioCodec& c : codecs) {
149 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200151 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152 }
153 return true;
154 }
155 }
156 return false;
157}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000158
solenberg0b675462015-10-09 01:37:09 -0700159bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
160 if (codecs.empty()) {
161 return true;
162 }
163 std::vector<int> payload_types;
164 for (const AudioCodec& codec : codecs) {
165 payload_types.push_back(codec.id);
166 }
167 std::sort(payload_types.begin(), payload_types.end());
168 auto it = std::unique(payload_types.begin(), payload_types.end());
169 return it == payload_types.end();
170}
171
Minyue Li7100dcd2015-03-27 05:05:59 +0100172// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800173bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100174 int value;
175 return codec.GetParam(feature, &value) && value == 1;
176}
177
178// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
179// otherwise. If the value (either from params or codec.bitrate) <=0, use the
180// default configuration. If the value is beyond feasible bit rate of Opus,
181// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700182int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100183 int bitrate = 0;
184 bool use_param = true;
185 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
186 bitrate = codec.bitrate;
187 use_param = false;
188 }
189 if (bitrate <= 0) {
190 if (max_playback_rate <= 8000) {
191 bitrate = kOpusBitrateNb;
192 } else if (max_playback_rate <= 16000) {
193 bitrate = kOpusBitrateWb;
194 } else {
195 bitrate = kOpusBitrateFb;
196 }
197
198 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
199 bitrate *= 2;
200 }
201 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
202 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
203 std::string rate_source =
204 use_param ? "Codec parameter \"maxaveragebitrate\"" :
205 "Supplied Opus bitrate";
206 LOG(LS_WARNING) << rate_source
207 << " is invalid and is replaced by: "
208 << bitrate;
209 }
210 return bitrate;
211}
212
213// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
214// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700215int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100216 int value;
217 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
218 return value;
219 }
220 return kOpusDefaultMaxPlaybackRate;
221}
222
solenbergd97ec302015-10-07 01:40:33 -0700223void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100224 bool* enable_codec_fec, int* max_playback_rate,
225 bool* enable_codec_dtx) {
226 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
227 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
228 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
229
230 // If OPUS, change what we send according to the "stereo" codec
231 // parameter, and not the "channels" parameter. We set
232 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
233 // the bitrate is not specified, i.e. is <= zero, we set it to the
234 // appropriate default value for mono or stereo Opus.
235
236 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
237 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
238}
239
solenberg566ef242015-11-06 15:34:49 -0800240webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
241 webrtc::AudioState::Config config;
242 config.voice_engine = voe_wrapper->engine();
243 return config;
244}
245
solenberg26c8c912015-11-27 04:00:25 -0800246class WebRtcVoiceCodecs final {
247 public:
248 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
249 // list and add a test which verifies VoE supports the listed codecs.
250 static std::vector<AudioCodec> SupportedCodecs() {
solenberg26c8c912015-11-27 04:00:25 -0800251 std::vector<AudioCodec> result;
deadbeef67cf2c12016-04-13 10:07:16 -0700252 // Iterate first over our preferred codecs list, so that the results are
253 // added in order of preference.
254 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
255 const CodecPref* pref = &kCodecPrefs[i];
256 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
257 // Change the sample rate of G722 to 8000 to match SDP.
258 MaybeFixupG722(&voe_codec, 8000);
259 // Skip uncompressed formats.
260 if (IsCodec(voe_codec, kL16CodecName)) {
261 continue;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000262 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000263
deadbeef67cf2c12016-04-13 10:07:16 -0700264 if (!IsCodec(voe_codec, pref->name) ||
265 pref->clockrate != voe_codec.plfreq ||
266 pref->channels != voe_codec.channels) {
267 // Not a match.
268 continue;
269 }
270
271 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
272 voe_codec.rate, voe_codec.channels);
273 LOG(LS_INFO) << "Adding supported codec: " << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100274 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000275 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000276 codec.bitrate = 0;
277 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100278 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000279 // Only add fmtp parameters that differ from the spec.
280 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
281 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000282 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000283 }
284 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
285 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000286 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000287 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000288 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800289 codec.AddFeedbackParam(
290 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000291
292 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000293 // when they can be set to values other than the default.
294 }
solenberg26c8c912015-11-27 04:00:25 -0800295 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000296 }
297 }
solenberg26c8c912015-11-27 04:00:25 -0800298 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000299 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000300
solenberg26c8c912015-11-27 04:00:25 -0800301 static bool ToCodecInst(const AudioCodec& in,
302 webrtc::CodecInst* out) {
303 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
304 // Change the sample rate of G722 to 8000 to match SDP.
305 MaybeFixupG722(&voe_codec, 8000);
306 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
deadbeef67cf2c12016-04-13 10:07:16 -0700307 voe_codec.rate, voe_codec.channels);
solenberg26c8c912015-11-27 04:00:25 -0800308 bool multi_rate = IsCodecMultiRate(voe_codec);
309 // Allow arbitrary rates for ISAC to be specified.
310 if (multi_rate) {
311 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
312 codec.bitrate = 0;
313 }
314 if (codec.Matches(in)) {
315 if (out) {
316 // Fixup the payload type.
317 voe_codec.pltype = in.id;
318
319 // Set bitrate if specified.
320 if (multi_rate && in.bitrate != 0) {
321 voe_codec.rate = in.bitrate;
322 }
323
324 // Reset G722 sample rate to 16000 to match WebRTC.
325 MaybeFixupG722(&voe_codec, 16000);
326
327 // Apply codec-specific settings.
328 if (IsCodec(codec, kIsacCodecName)) {
329 // If ISAC and an explicit bitrate is not specified,
330 // enable auto bitrate adjustment.
331 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
332 }
333 *out = voe_codec;
334 }
335 return true;
336 }
337 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000338 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000339 }
solenberg26c8c912015-11-27 04:00:25 -0800340
341 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
342 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
343 if (IsCodec(codec, kCodecPrefs[i].name) &&
344 kCodecPrefs[i].clockrate == codec.plfreq) {
345 return kCodecPrefs[i].is_multi_rate;
346 }
347 }
348 return false;
349 }
350
351 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
352 // codec pacsize if it's valid, or we will pick the next smallest value we
353 // support.
354 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
355 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
356 for (const CodecPref& codec_pref : kCodecPrefs) {
357 if ((IsCodec(*codec, codec_pref.name) &&
358 codec_pref.clockrate == codec->plfreq) ||
359 IsCodec(*codec, kG722CodecName)) {
360 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
361 if (packet_size_ms) {
362 // Convert unit from milli-seconds to samples.
363 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
364 return true;
365 }
366 }
367 }
368 return false;
369 }
370
stefanba4c0e42016-02-04 04:12:24 -0800371 static const AudioCodec* GetPreferredCodec(
372 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800373 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800374 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800375 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800376 RTC_DCHECK(red_payload_type);
377 // Select the preferred send codec (the first non-telephone-event/CN codec).
378 for (const AudioCodec& codec : codecs) {
379 *red_payload_type = -1;
380 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
381 // Skip telephone-event/CN codec, which will be handled later.
382 continue;
383 }
384
385 // We'll use the first codec in the list to actually send audio data.
386 // Be sure to use the payload type requested by the remote side.
387 // "red", for RED audio, is a special case where the actual codec to be
388 // used is specified in params.
389 const AudioCodec* found_codec = &codec;
390 if (IsCodec(*found_codec, kRedCodecName)) {
391 // Parse out the RED parameters. If we fail, just ignore RED;
392 // we don't support all possible params/usage scenarios.
393 *red_payload_type = codec.id;
394 found_codec = GetRedSendCodec(*found_codec, codecs);
395 if (!found_codec) {
396 continue;
397 }
398 }
399 // Ignore codecs we don't know about. The negotiation step should prevent
400 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800401 webrtc::CodecInst voe_codec = {0};
402 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800403 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
404 continue;
405 }
solenberg72e29d22016-03-08 06:35:16 -0800406 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800407 return found_codec;
408 }
409 return nullptr;
410 }
411
solenberg26c8c912015-11-27 04:00:25 -0800412 private:
413 static const int kMaxNumPacketSize = 6;
414 struct CodecPref {
415 const char* name;
416 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800417 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800418 int payload_type;
419 bool is_multi_rate;
420 int packet_sizes_ms[kMaxNumPacketSize];
421 };
422 // Note: keep the supported packet sizes in ascending order.
423 static const CodecPref kCodecPrefs[12];
424
425 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
426 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
427 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
428 if (packet_size_ms && packet_size_ms <= ptime_ms) {
429 selected_packet_size_ms = packet_size_ms;
430 }
431 }
432 return selected_packet_size_ms;
433 }
434
435 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
436 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
437 // codec.
438 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
439 if (IsCodec(*voe_codec, kG722CodecName)) {
440 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
441 // has changed, and this special case is no longer needed.
442 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
443 voe_codec->plfreq = new_plfreq;
444 }
445 }
stefanba4c0e42016-02-04 04:12:24 -0800446
447 static const AudioCodec* GetRedSendCodec(
448 const AudioCodec& red_codec,
449 const std::vector<AudioCodec>& all_codecs) {
450 // Get the RED encodings from the parameter with no name. This may
451 // change based on what is discussed on the Jingle list.
452 // The encoding parameter is of the form "a/b"; we only support where
453 // a == b. Verify this and parse out the value into red_pt.
454 // If the parameter value is absent (as it will be until we wire up the
455 // signaling of this message), use the second codec specified (i.e. the
456 // one after "red") as the encoding parameter.
457 int red_pt = -1;
458 std::string red_params;
459 CodecParameterMap::const_iterator it = red_codec.params.find("");
460 if (it != red_codec.params.end()) {
461 red_params = it->second;
462 std::vector<std::string> red_pts;
463 if (rtc::split(red_params, '/', &red_pts) != 2 ||
464 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
465 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
466 return nullptr;
467 }
468 } else if (red_codec.params.empty()) {
469 LOG(LS_WARNING) << "RED params not present, using defaults";
470 if (all_codecs.size() > 1) {
471 red_pt = all_codecs[1].id;
472 }
473 }
474
475 // Try to find red_pt in |codecs|.
476 for (const AudioCodec& codec : all_codecs) {
477 if (codec.id == red_pt) {
478 return &codec;
479 }
480 }
481 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
482 return nullptr;
483 }
solenberg26c8c912015-11-27 04:00:25 -0800484};
485
486const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
487 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
488 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
489 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
490 // G722 should be advertised as 8000 Hz because of the RFC "bug".
491 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
492 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
493 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
494 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
495 { kCnCodecName, 32000, 1, 106, false, { } },
496 { kCnCodecName, 16000, 1, 105, false, { } },
497 { kCnCodecName, 8000, 1, 13, false, { } },
498 { kRedCodecName, 8000, 1, 127, false, { } },
499 { kDtmfCodecName, 8000, 1, 126, false, { } },
500};
501} // namespace {
502
503bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
504 webrtc::CodecInst* out) {
505 return WebRtcVoiceCodecs::ToCodecInst(in, out);
506}
507
solenbergff976312016-03-30 23:28:51 -0700508WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm)
509 : WebRtcVoiceEngine(adm, new VoEWrapper()) {
510 audio_state_ = webrtc::AudioState::Create(MakeAudioStateConfig(voe()));
solenberg26c8c912015-11-27 04:00:25 -0800511}
512
solenbergff976312016-03-30 23:28:51 -0700513WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm,
514 VoEWrapper* voe_wrapper)
515 : adm_(adm), voe_wrapper_(voe_wrapper) {
solenberg26c8c912015-11-27 04:00:25 -0800516 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700517 LOG(LS_INFO) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
518 RTC_DCHECK(voe_wrapper);
solenberg26c8c912015-11-27 04:00:25 -0800519
520 signal_thread_checker_.DetachFromThread();
solenberg26c8c912015-11-27 04:00:25 -0800521
522 // Load our audio codec list.
solenbergff976312016-03-30 23:28:51 -0700523 LOG(LS_INFO) << "Supported codecs in order of preference:";
solenberg26c8c912015-11-27 04:00:25 -0800524 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
solenbergff976312016-03-30 23:28:51 -0700525 for (const AudioCodec& codec : codecs_) {
526 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000527 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528
solenbergff976312016-03-30 23:28:51 -0700529 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000530
solenbergff976312016-03-30 23:28:51 -0700531 // Temporarily turn logging level up for the Init() call.
532 webrtc::Trace::SetTraceCallback(this);
solenbergbd138382015-11-20 16:08:07 -0800533 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800534 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
solenbergff976312016-03-30 23:28:51 -0700535 RTC_CHECK_EQ(0, voe_wrapper_->base()->Init(adm_.get()));
solenbergbd138382015-11-20 16:08:07 -0800536 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537
solenbergff976312016-03-30 23:28:51 -0700538 // No ADM supplied? Get the default one from VoE.
539 if (!adm_) {
540 adm_ = voe_wrapper_->base()->audio_device_module();
541 }
542 RTC_DCHECK(adm_);
543
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000544 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800545 // calling ApplyOptions or the default will be overwritten.
solenbergff976312016-03-30 23:28:51 -0700546 int error = voe_wrapper_->processing()->GetAgcConfig(default_agc_config_);
547 RTC_DCHECK_EQ(0, error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000548
solenberg0f7d2932016-01-15 01:40:39 -0800549 // Set default engine options.
550 {
551 AudioOptions options;
552 options.echo_cancellation = rtc::Optional<bool>(true);
553 options.auto_gain_control = rtc::Optional<bool>(true);
554 options.noise_suppression = rtc::Optional<bool>(true);
555 options.highpass_filter = rtc::Optional<bool>(true);
556 options.stereo_swapping = rtc::Optional<bool>(false);
557 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
558 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
559 options.typing_detection = rtc::Optional<bool>(true);
560 options.adjust_agc_delta = rtc::Optional<int>(0);
561 options.experimental_agc = rtc::Optional<bool>(false);
562 options.extended_filter_aec = rtc::Optional<bool>(false);
563 options.delay_agnostic_aec = rtc::Optional<bool>(false);
564 options.experimental_ns = rtc::Optional<bool>(false);
solenbergff976312016-03-30 23:28:51 -0700565 bool error = ApplyOptions(options);
566 RTC_DCHECK(error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567 }
568
solenberg246b8172015-12-08 09:50:23 -0800569 SetDefaultDevices();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000570}
571
solenbergff976312016-03-30 23:28:51 -0700572WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800573 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700574 LOG(LS_INFO) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000575 StopAecDump();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 voe_wrapper_->base()->Terminate();
solenbergff976312016-03-30 23:28:51 -0700577 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000578}
579
solenberg566ef242015-11-06 15:34:49 -0800580rtc::scoped_refptr<webrtc::AudioState>
581 WebRtcVoiceEngine::GetAudioState() const {
582 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
583 return audio_state_;
584}
585
nisse51542be2016-02-12 02:27:06 -0800586VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
587 webrtc::Call* call,
588 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200589 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800590 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800591 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000592}
593
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000594bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800595 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700596 LOG(LS_INFO) << "WebRtcVoiceEngine::ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800597 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800598
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000599 // kEcConference is AEC with high suppression.
600 webrtc::EcModes ec_mode = webrtc::kEcConference;
601 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
602 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
603 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700604 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000605 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700606 << *options.aecm_generate_comfort_noise
607 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000608 }
609
kjellanderfcfc8042016-01-14 11:01:09 -0800610#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000611 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100612 options.echo_cancellation = rtc::Optional<bool>(false);
613 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200614 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000615#elif defined(ANDROID)
616 ec_mode = webrtc::kEcAecm;
617#endif
618
kjellanderfcfc8042016-01-14 11:01:09 -0800619#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000620 // Set the AGC mode for iOS as well despite disabling it above, to avoid
621 // unsupported configuration errors from webrtc.
622 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100623 options.typing_detection = rtc::Optional<bool>(false);
624 options.experimental_agc = rtc::Optional<bool>(false);
625 options.extended_filter_aec = rtc::Optional<bool>(false);
626 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000627#endif
628
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100629 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
630 // where the feature is not supported.
631 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800632#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700633 if (options.delay_agnostic_aec) {
634 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100635 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100636 options.echo_cancellation = rtc::Optional<bool>(true);
637 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100638 ec_mode = webrtc::kEcConference;
639 }
640 }
641#endif
642
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000643 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
644
kwiberg102c6a62015-10-30 02:47:38 -0700645 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000646 // Check if platform supports built-in EC. Currently only supported on
647 // Android and in combination with Java based audio layer.
648 // TODO(henrika): investigate possibility to support built-in EC also
649 // in combination with Open SL ES audio.
solenberg5b5129a2016-04-08 05:35:48 -0700650 const bool built_in_aec = adm()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200651 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200652 // Built-in EC exists on this device and use_delay_agnostic_aec is not
653 // overriding it. Enable/Disable it according to the echo_cancellation
654 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200655 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700656 *options.echo_cancellation && !use_delay_agnostic_aec;
solenberg5b5129a2016-04-08 05:35:48 -0700657 if (adm()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
Bjorn Volcker73f72102015-06-03 14:50:15 +0200658 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100659 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000660 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100661 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000662 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
663 }
664 }
kwiberg102c6a62015-10-30 02:47:38 -0700665 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
666 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000667 return false;
668 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700669 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200670 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000671 }
672#if !defined(ANDROID)
673 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700674 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
675 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000676 return false;
677 }
678#endif
679 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700680 bool cn = options.aecm_generate_comfort_noise.value_or(false);
681 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
682 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000683 return false;
684 }
685 }
686 }
687
kwiberg102c6a62015-10-30 02:47:38 -0700688 if (options.auto_gain_control) {
solenberg5b5129a2016-04-08 05:35:48 -0700689 const bool built_in_agc = adm()->BuiltInAGCIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200690 if (built_in_agc) {
solenberg5b5129a2016-04-08 05:35:48 -0700691 if (adm()->EnableBuiltInAGC(*options.auto_gain_control) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700692 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200693 // Disable internal software AGC if built-in AGC is enabled,
694 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100695 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200696 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
697 }
698 }
kwiberg102c6a62015-10-30 02:47:38 -0700699 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
700 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000701 return false;
702 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700703 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
704 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000705 }
706 }
707
kwiberg102c6a62015-10-30 02:47:38 -0700708 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
709 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000710 // Override default_agc_config_. Generally, an unset option means "leave
711 // the VoE bits alone" in this function, so we want whatever is set to be
712 // stored as the new "default". If we didn't, then setting e.g.
713 // tx_agc_target_dbov would reset digital compression gain and limiter
714 // settings.
715 // Also, if we don't update default_agc_config_, then adjust_agc_delta
716 // would be an offset from the original values, and not whatever was set
717 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700718 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
719 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000720 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700721 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000722 default_agc_config_.digitalCompressionGaindB);
723 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700724 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000725 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
726 LOG_RTCERR3(SetAgcConfig,
727 default_agc_config_.targetLeveldBOv,
728 default_agc_config_.digitalCompressionGaindB,
729 default_agc_config_.limiterEnable);
730 return false;
731 }
732 }
733
kwiberg102c6a62015-10-30 02:47:38 -0700734 if (options.noise_suppression) {
solenberg5b5129a2016-04-08 05:35:48 -0700735 const bool built_in_ns = adm()->BuiltInNSIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200736 if (built_in_ns) {
solenberg5b5129a2016-04-08 05:35:48 -0700737 if (adm()->EnableBuiltInNS(*options.noise_suppression) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700738 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200739 // Disable internal software NS if built-in NS is enabled,
740 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100741 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200742 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
743 }
744 }
kwiberg102c6a62015-10-30 02:47:38 -0700745 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
746 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000747 return false;
748 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700749 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200750 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000751 }
752 }
753
kwiberg102c6a62015-10-30 02:47:38 -0700754 if (options.highpass_filter) {
755 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
756 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
757 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000758 return false;
759 }
760 }
761
kwiberg102c6a62015-10-30 02:47:38 -0700762 if (options.stereo_swapping) {
763 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
764 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
765 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
766 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000767 return false;
768 }
769 }
770
kwiberg102c6a62015-10-30 02:47:38 -0700771 if (options.audio_jitter_buffer_max_packets) {
772 LOG(LS_INFO) << "NetEq capacity is "
773 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200774 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700775 new webrtc::NetEqCapacityConfig(
776 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200777 }
778
kwiberg102c6a62015-10-30 02:47:38 -0700779 if (options.audio_jitter_buffer_fast_accelerate) {
780 LOG(LS_INFO) << "NetEq fast mode? "
781 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200782 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700783 new webrtc::NetEqFastAccelerate(
784 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200785 }
786
kwiberg102c6a62015-10-30 02:47:38 -0700787 if (options.typing_detection) {
788 LOG(LS_INFO) << "Typing detection is enabled? "
789 << *options.typing_detection;
790 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000791 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700792 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000793 }
794 }
795
kwiberg102c6a62015-10-30 02:47:38 -0700796 if (options.adjust_agc_delta) {
797 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
798 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000799 return false;
800 }
801 }
802
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000803 webrtc::Config config;
804
kwiberg102c6a62015-10-30 02:47:38 -0700805 if (options.delay_agnostic_aec)
806 delay_agnostic_aec_ = options.delay_agnostic_aec;
807 if (delay_agnostic_aec_) {
808 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700809 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700810 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100811 }
812
kwiberg102c6a62015-10-30 02:47:38 -0700813 if (options.extended_filter_aec) {
814 extended_filter_aec_ = options.extended_filter_aec;
815 }
816 if (extended_filter_aec_) {
817 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200818 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700819 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000820 }
821
kwiberg102c6a62015-10-30 02:47:38 -0700822 if (options.experimental_ns) {
823 experimental_ns_ = options.experimental_ns;
824 }
825 if (experimental_ns_) {
826 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000827 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700828 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000829 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000830
831 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
832 // returns NULL on audio_processing().
833 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
834 if (audioproc) {
835 audioproc->SetExtraOptions(config);
836 }
837
kwiberg102c6a62015-10-30 02:47:38 -0700838 if (options.recording_sample_rate) {
839 LOG(LS_INFO) << "Recording sample rate is "
840 << *options.recording_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700841 if (adm()->SetRecordingSampleRate(*options.recording_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700842 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000843 }
844 }
845
kwiberg102c6a62015-10-30 02:47:38 -0700846 if (options.playout_sample_rate) {
847 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700848 if (adm()->SetPlayoutSampleRate(*options.playout_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700849 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000850 }
851 }
852
853 return true;
854}
855
solenberg246b8172015-12-08 09:50:23 -0800856void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800857 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800858#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800859 int in_id = kDefaultAudioDeviceId;
860 int out_id = kDefaultAudioDeviceId;
861 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
862 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000863
solenbergc1a1b352015-09-22 13:31:20 -0700864 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800865 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
866 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000867 ret = false;
868 }
solenberg246b8172015-12-08 09:50:23 -0800869 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
870 if (ap) {
871 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 }
873
solenberg246b8172015-12-08 09:50:23 -0800874 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
875 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 ret = false;
877 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800880 LOG(LS_INFO) << "Set microphone to (id=" << in_id
881 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882 }
kjellanderfcfc8042016-01-14 11:01:09 -0800883#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800887 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 unsigned int ulevel;
889 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
890 LOG_RTCERR1(GetSpeakerVolume, level);
891 return false;
892 }
893 *level = ulevel;
894 return true;
895}
896
897bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800898 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700899 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
901 LOG_RTCERR1(SetSpeakerVolume, level);
902 return false;
903 }
904 return true;
905}
906
907int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800908 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909 unsigned int ulevel;
910 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
911 static_cast<int>(ulevel) : -1;
912}
913
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800915 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916 return codecs_;
917}
918
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100919RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800920 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100921 RtpCapabilities capabilities;
922 capabilities.header_extensions.push_back(RtpHeaderExtension(
923 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
924 capabilities.header_extensions.push_back(
925 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
926 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800927 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
928 "Enabled") {
929 capabilities.header_extensions.push_back(RtpHeaderExtension(
930 kRtpTransportSequenceNumberHeaderExtension,
931 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
932 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100933 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800937 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 return voe_wrapper_->error();
939}
940
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
942 int length) {
solenberg566ef242015-11-06 15:34:49 -0800943 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000946 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000950 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000952 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
solenberg72e29d22016-03-08 06:35:16 -0800954 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (length < 72) {
956 std::string msg(trace, length);
957 LOG(LS_ERROR) << "Malformed webrtc log message: ";
958 LOG_V(sev) << msg;
959 } else {
960 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +0200961 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 }
963}
964
solenberg63b34542015-09-29 06:06:31 -0700965void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800966 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
967 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 channels_.push_back(channel);
969}
970
solenberg63b34542015-09-29 06:06:31 -0700971void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800972 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -0700973 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -0800974 RTC_DCHECK(it != channels_.end());
975 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976}
977
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978// Adjusts the default AGC target level by the specified delta.
979// NB: If we start messing with other config fields, we'll want
980// to save the current webrtc::AgcConfig as well.
981bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -0800982 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 webrtc::AgcConfig config = default_agc_config_;
984 config.targetLeveldBOv -= delta;
985
986 LOG(LS_INFO) << "Adjusting AGC level from default -"
987 << default_agc_config_.targetLeveldBOv << "dB to -"
988 << config.targetLeveldBOv << "dB";
989
990 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
991 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
992 return false;
993 }
994 return true;
995}
996
ivocd66b44d2016-01-15 03:06:36 -0800997bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
998 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -0800999 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001000 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001001 if (!aec_dump_file_stream) {
1002 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001003 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001004 LOG(LS_WARNING) << "Could not close file.";
1005 return false;
1006 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001007 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001008 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1009 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001010 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001011 LOG_RTCERR0(StartDebugRecording);
1012 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001013 return false;
1014 }
1015 is_dumping_aec_ = true;
1016 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001017}
1018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001020 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 if (!is_dumping_aec_) {
1022 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001023 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1024 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001025 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 } else {
1027 is_dumping_aec_ = true;
1028 }
1029 }
1030}
1031
1032void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001033 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 if (is_dumping_aec_) {
1035 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001036 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 webrtc::AudioProcessing::kNoError) {
1038 LOG_RTCERR0(StopDebugRecording);
1039 }
1040 is_dumping_aec_ = false;
1041 }
1042}
1043
ivoc112a3d82015-10-16 02:22:18 -07001044bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001045 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001046 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1047 if (event_log) {
1048 return event_log->StartLogging(file);
1049 }
1050 LOG_RTCERR0(StartRtcEventLog);
1051 return false;
ivoc112a3d82015-10-16 02:22:18 -07001052}
1053
1054void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001055 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001056 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1057 if (event_log) {
1058 event_log->StopLogging();
1059 return;
1060 }
1061 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001062}
1063
solenberg0a617e22015-10-20 15:49:38 -07001064int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001065 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001066 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001067}
1068
solenberg5b5129a2016-04-08 05:35:48 -07001069webrtc::AudioDeviceModule* WebRtcVoiceEngine::adm() {
1070 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1071 RTC_DCHECK(adm_);
1072 return adm_;
1073}
1074
solenbergc96df772015-10-21 13:01:53 -07001075class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001076 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001077 public:
skvlade0d46372016-04-07 22:59:22 -07001078 WebRtcAudioSendStream(int ch,
1079 webrtc::AudioTransport* voe_audio_transport,
1080 uint32_t ssrc,
1081 const std::string& c_name,
solenberg3a941542015-11-16 07:34:50 -08001082 const std::vector<webrtc::RtpExtension>& extensions,
1083 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001084 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001085 call_(call),
skvlade0d46372016-04-07 22:59:22 -07001086 config_(nullptr),
1087 rtp_parameters_(CreateRtpParametersWithOneEncoding()) {
solenberg85a04962015-10-27 03:35:21 -07001088 RTC_DCHECK_GE(ch, 0);
1089 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1090 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001091 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001092 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001093 config_.rtp.ssrc = ssrc;
1094 config_.rtp.c_name = c_name;
1095 config_.voe_channel_id = ch;
1096 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001097 }
solenberg3a941542015-11-16 07:34:50 -08001098
solenbergc96df772015-10-21 13:01:53 -07001099 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001100 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001101 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001102 call_->DestroyAudioSendStream(stream_);
1103 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001104
solenberg3a941542015-11-16 07:34:50 -08001105 void RecreateAudioSendStream(
1106 const std::vector<webrtc::RtpExtension>& extensions) {
1107 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1108 if (stream_) {
1109 call_->DestroyAudioSendStream(stream_);
1110 stream_ = nullptr;
1111 }
1112 config_.rtp.extensions = extensions;
1113 RTC_DCHECK(!stream_);
1114 stream_ = call_->CreateAudioSendStream(config_);
1115 RTC_CHECK(stream_);
solenberg6d6e7c52016-04-13 09:07:30 -07001116 UpdateSendState();
solenberg3a941542015-11-16 07:34:50 -08001117 }
1118
solenberg8842c3e2016-03-11 03:06:41 -08001119 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001120 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1121 RTC_DCHECK(stream_);
1122 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1123 }
1124
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001125 void SetSend(bool send) {
1126 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1127 send_ = send;
1128 UpdateSendState();
1129 }
1130
solenberg3a941542015-11-16 07:34:50 -08001131 webrtc::AudioSendStream::Stats GetStats() const {
1132 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1133 RTC_DCHECK(stream_);
1134 return stream_->GetStats();
1135 }
1136
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001137 // Starts the sending by setting ourselves as a sink to the AudioSource to
1138 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001139 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001140 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001141 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001142 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001143 RTC_DCHECK(source);
1144 if (source_) {
1145 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001146 return;
1147 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001148 source->SetSink(this);
1149 source_ = source;
1150 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001151 }
1152
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001153 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001154 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001155 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001156 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001157 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001158 if (source_) {
1159 source_->SetSink(nullptr);
1160 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001161 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001162 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001163 }
1164
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001165 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001166 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001167 void OnData(const void* audio_data,
1168 int bits_per_sample,
1169 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001170 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001171 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001172 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001173 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001174 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001175 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001176 audio_data,
1177 bits_per_sample,
1178 sample_rate,
1179 number_of_channels,
1180 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001181 }
1182
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001183 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001184 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001185 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001186 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001187 // Set |source_| to nullptr to make sure no more callback will get into
1188 // the source.
1189 source_ = nullptr;
1190 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001191 }
1192
1193 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001194 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001195 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001196 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001197 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001198
skvlade0d46372016-04-07 22:59:22 -07001199 const webrtc::RtpParameters& rtp_parameters() const {
1200 return rtp_parameters_;
1201 }
1202
1203 void set_rtp_parameters(const webrtc::RtpParameters& parameters) {
1204 RTC_CHECK_EQ(1UL, parameters.encodings.size());
1205 rtp_parameters_ = parameters;
1206 }
1207
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001208 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001209 void UpdateSendState() {
1210 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1211 RTC_DCHECK(stream_);
1212 if (send_ && source_ != nullptr) {
1213 stream_->Start();
1214 } else { // !send || source_ = nullptr
1215 stream_->Stop();
1216 }
1217 }
1218
solenberg566ef242015-11-06 15:34:49 -08001219 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001220 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001221 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1222 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001223 webrtc::AudioSendStream::Config config_;
1224 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1225 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001226 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001227
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001228 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001229 // PeerConnection will make sure invalidating the pointer before the object
1230 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001231 AudioSource* source_ = nullptr;
1232 bool send_ = false;
skvlade0d46372016-04-07 22:59:22 -07001233 webrtc::RtpParameters rtp_parameters_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001234
solenbergc96df772015-10-21 13:01:53 -07001235 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1236};
1237
1238class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1239 public:
stefanba4c0e42016-02-04 04:12:24 -08001240 WebRtcAudioReceiveStream(int ch,
1241 uint32_t remote_ssrc,
1242 uint32_t local_ssrc,
1243 bool use_transport_cc,
1244 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001245 const std::vector<webrtc::RtpExtension>& extensions,
1246 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001247 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001248 RTC_DCHECK_GE(ch, 0);
1249 RTC_DCHECK(call);
1250 config_.rtp.remote_ssrc = remote_ssrc;
1251 config_.rtp.local_ssrc = local_ssrc;
1252 config_.voe_channel_id = ch;
1253 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001254 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001255 }
solenbergc96df772015-10-21 13:01:53 -07001256
solenberg7add0582015-11-20 09:59:34 -08001257 ~WebRtcAudioReceiveStream() {
1258 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1259 call_->DestroyAudioReceiveStream(stream_);
1260 }
1261
1262 void RecreateAudioReceiveStream(
1263 const std::vector<webrtc::RtpExtension>& extensions) {
1264 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001265 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001266 }
stefanba4c0e42016-02-04 04:12:24 -08001267 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001268 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001269 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001270 }
1271
1272 webrtc::AudioReceiveStream::Stats GetStats() const {
1273 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1274 RTC_DCHECK(stream_);
1275 return stream_->GetStats();
1276 }
1277
1278 int channel() const {
1279 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1280 return config_.voe_channel_id;
1281 }
solenbergc96df772015-10-21 13:01:53 -07001282
kwiberg686a8ef2016-02-26 03:00:35 -08001283 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001284 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001285 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001286 }
1287
solenbergc96df772015-10-21 13:01:53 -07001288 private:
stefanba4c0e42016-02-04 04:12:24 -08001289 void RecreateAudioReceiveStream(
1290 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001291 const std::vector<webrtc::RtpExtension>& extensions) {
1292 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1293 if (stream_) {
1294 call_->DestroyAudioReceiveStream(stream_);
1295 stream_ = nullptr;
1296 }
1297 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001298 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001299 RTC_DCHECK(!stream_);
1300 stream_ = call_->CreateAudioReceiveStream(config_);
1301 RTC_CHECK(stream_);
1302 }
1303
1304 rtc::ThreadChecker worker_thread_checker_;
1305 webrtc::Call* call_ = nullptr;
1306 webrtc::AudioReceiveStream::Config config_;
1307 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1308 // configuration changes.
1309 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001310
1311 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001312};
1313
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001314WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001315 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001316 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001317 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001318 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001319 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001320 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001321 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001322 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323}
1324
1325WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001326 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001327 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001328 // TODO(solenberg): Should be able to delete the streams directly, without
1329 // going through RemoveNnStream(), once stream objects handle
1330 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001331 while (!send_streams_.empty()) {
1332 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001333 }
solenberg7add0582015-11-20 09:59:34 -08001334 while (!recv_streams_.empty()) {
1335 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336 }
solenberg0a617e22015-10-20 15:49:38 -07001337 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338}
1339
nisse51542be2016-02-12 02:27:06 -08001340rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1341 return kAudioDscpValue;
1342}
1343
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001344bool WebRtcVoiceMediaChannel::SetSendParameters(
1345 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001346 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001347 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001348 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1349 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001350 // TODO(pthatcher): Refactor this to be more clean now that we have
1351 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001352
1353 if (!SetSendCodecs(params.codecs)) {
1354 return false;
1355 }
1356
solenberg7e4e01a2015-12-02 08:05:01 -08001357 if (!ValidateRtpExtensions(params.extensions)) {
1358 return false;
1359 }
1360 std::vector<webrtc::RtpExtension> filtered_extensions =
1361 FilterRtpExtensions(params.extensions,
1362 webrtc::RtpExtension::IsSupportedForAudio, true);
1363 if (send_rtp_extensions_ != filtered_extensions) {
1364 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001365 for (auto& it : send_streams_) {
1366 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1367 }
1368 }
1369
skvlade0d46372016-04-07 22:59:22 -07001370 if (!SetSendBitrate(params.max_bandwidth_bps)) {
solenberg3a941542015-11-16 07:34:50 -08001371 return false;
1372 }
1373 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001374}
1375
1376bool WebRtcVoiceMediaChannel::SetRecvParameters(
1377 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001378 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001379 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001380 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1381 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001382 // TODO(pthatcher): Refactor this to be more clean now that we have
1383 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001384
1385 if (!SetRecvCodecs(params.codecs)) {
1386 return false;
1387 }
1388
solenberg7e4e01a2015-12-02 08:05:01 -08001389 if (!ValidateRtpExtensions(params.extensions)) {
1390 return false;
1391 }
1392 std::vector<webrtc::RtpExtension> filtered_extensions =
1393 FilterRtpExtensions(params.extensions,
1394 webrtc::RtpExtension::IsSupportedForAudio, false);
1395 if (recv_rtp_extensions_ != filtered_extensions) {
1396 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001397 for (auto& it : recv_streams_) {
1398 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1399 }
1400 }
solenberg7add0582015-11-20 09:59:34 -08001401 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001402}
1403
skvlade0d46372016-04-07 22:59:22 -07001404webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpParameters(
1405 uint32_t ssrc) const {
1406 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1407 auto it = send_streams_.find(ssrc);
1408 if (it == send_streams_.end()) {
1409 LOG(LS_WARNING) << "Attempting to get RTP parameters for stream with ssrc "
1410 << ssrc << " which doesn't exist.";
1411 return webrtc::RtpParameters();
1412 }
1413
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001414 webrtc::RtpParameters rtp_params = it->second->rtp_parameters();
1415 // Need to add the common list of codecs to the send stream-specific
1416 // RTP parameters.
1417 for (const AudioCodec& codec : send_codecs_) {
1418 rtp_params.codecs.push_back(codec.ToCodecParameters());
1419 }
1420 return rtp_params;
skvlade0d46372016-04-07 22:59:22 -07001421}
1422
1423bool WebRtcVoiceMediaChannel::SetRtpParameters(
1424 uint32_t ssrc,
1425 const webrtc::RtpParameters& parameters) {
1426 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1427 if (!ValidateRtpParameters(parameters)) {
1428 return false;
1429 }
1430 auto it = send_streams_.find(ssrc);
1431 if (it == send_streams_.end()) {
1432 LOG(LS_WARNING) << "Attempting to set RTP parameters for stream with ssrc "
1433 << ssrc << " which doesn't exist.";
1434 return false;
1435 }
1436
1437 if (!SetChannelParameters(it->second->channel(), parameters)) {
1438 LOG(LS_WARNING) << "Failed to set RtpParameters.";
1439 return false;
1440 }
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001441 // Codecs are handled at the WebRtcVoiceMediaChannel level.
1442 webrtc::RtpParameters reduced_params = parameters;
1443 reduced_params.codecs.clear();
1444 it->second->set_rtp_parameters(reduced_params);
skvlade0d46372016-04-07 22:59:22 -07001445 return true;
1446}
1447
1448bool WebRtcVoiceMediaChannel::ValidateRtpParameters(
1449 const webrtc::RtpParameters& rtp_parameters) {
1450 if (rtp_parameters.encodings.size() != 1) {
1451 LOG(LS_ERROR)
1452 << "Attempted to set RtpParameters without exactly one encoding";
1453 return false;
1454 }
1455 return true;
1456}
1457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001459 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 LOG(LS_INFO) << "Setting voice channel options: "
1461 << options.ToString();
1462
1463 // We retain all of the existing options, and apply the given ones
1464 // on top. This means there is no way to "clear" options such that
1465 // they go back to the engine default.
1466 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001467 if (!engine()->ApplyOptions(options_)) {
1468 LOG(LS_WARNING) <<
1469 "Failed to apply engine options during channel SetOptions.";
1470 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 LOG(LS_INFO) << "Set voice channel options. Current options: "
1473 << options_.ToString();
1474 return true;
1475}
1476
1477bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1478 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001479 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001480
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001482 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001483
1484 if (!VerifyUniquePayloadTypes(codecs)) {
1485 LOG(LS_ERROR) << "Codec payload types overlap.";
1486 return false;
1487 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488
1489 std::vector<AudioCodec> new_codecs;
1490 // Find all new codecs. We allow adding new codecs but don't allow changing
1491 // the payload type of codecs that is already configured since we might
1492 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001493 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001495 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1496 if (old_codec.id != codec.id) {
1497 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498 return false;
1499 }
1500 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001501 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502 }
1503 }
1504 if (new_codecs.empty()) {
1505 // There are no new codecs to configure. Already configured codecs are
1506 // never removed.
1507 return true;
1508 }
1509
1510 if (playout_) {
1511 // Receive codecs can not be changed while playing. So we temporarily
1512 // pause playout.
1513 PausePlayout();
1514 }
1515
solenberg26c8c912015-11-27 04:00:25 -08001516 bool result = true;
1517 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001518 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001519 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1520 LOG(LS_INFO) << ToString(codec);
1521 voe_codec.pltype = codec.id;
1522 for (const auto& ch : recv_streams_) {
1523 if (engine()->voe()->codec()->SetRecPayloadType(
1524 ch.second->channel(), voe_codec) == -1) {
1525 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1526 ToString(voe_codec));
1527 result = false;
1528 }
1529 }
1530 } else {
1531 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1532 result = false;
1533 break;
1534 }
1535 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001536 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 recv_codecs_ = codecs;
1538 }
1539
1540 if (desired_playout_ && !playout_) {
1541 ResumePlayout();
1542 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001543 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544}
1545
solenberg72e29d22016-03-08 06:35:16 -08001546// Utility function called from SetSendParameters() to extract current send
1547// codec settings from the given list of codecs (originally from SDP). Both send
1548// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001549bool WebRtcVoiceMediaChannel::SetSendCodecs(
1550 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001551 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001552 // TODO(solenberg): Validate input - that payload types don't overlap, are
1553 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001554 // redundant codecs etc - the same way it is done for
1555 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001556
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001557 // Find the DTMF telephone event "codec" payload type.
1558 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001559 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001560 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001561 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1562 return false;
1563 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001564 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1565 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001566 }
1567 }
1568
solenberg72e29d22016-03-08 06:35:16 -08001569 // Scan through the list to figure out the codec to use for sending, along
1570 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1571 // parameters.
1572 {
1573 SendCodecSpec send_codec_spec;
1574 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1575
1576 // Find send codec (the first non-telephone-event/CN codec).
1577 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1578 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1579 if (!codec) {
1580 LOG(LS_WARNING) << "Received empty list of codecs.";
1581 return false;
1582 }
1583
1584 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1585
1586 // This condition is apparently here because Opus does not support RED and
1587 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1588 // such limitations.
1589 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1590 if (send_codec_spec.red_payload_type == -1) {
1591 send_codec_spec.nack_enabled = HasNack(*codec);
1592 // For Opus as the send codec, we are to determine inband FEC, maximum
1593 // playback rate, and opus internal dtx.
1594 if (IsCodec(*codec, kOpusCodecName)) {
1595 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1596 &send_codec_spec.enable_codec_fec,
1597 &send_codec_spec.opus_max_playback_rate,
1598 &send_codec_spec.enable_opus_dtx);
1599 }
1600
1601 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1602 int ptime_ms = 0;
1603 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1604 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1605 &send_codec_spec.codec_inst, ptime_ms)) {
1606 LOG(LS_WARNING) << "Failed to set packet size for codec "
1607 << send_codec_spec.codec_inst.plname;
1608 return false;
1609 }
1610 }
1611 }
1612
1613 // Loop through the codecs list again to find the CN codec.
1614 // TODO(solenberg): Break out into a separate function?
1615 for (const AudioCodec& codec : codecs) {
1616 // Ignore codecs we don't know about. The negotiation step should prevent
1617 // this, but double-check to be sure.
1618 webrtc::CodecInst voe_codec = {0};
1619 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1620 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1621 continue;
1622 }
1623
1624 if (IsCodec(codec, kCnCodecName)) {
1625 // Turn voice activity detection/comfort noise on if supported.
1626 // Set the wideband CN payload type appropriately.
1627 // (narrowband always uses the static payload type 13).
1628 int cng_plfreq = -1;
1629 switch (codec.clockrate) {
1630 case 8000:
1631 case 16000:
1632 case 32000:
1633 cng_plfreq = codec.clockrate;
1634 break;
1635 default:
1636 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1637 << " not supported.";
1638 continue;
1639 }
1640 send_codec_spec.cng_payload_type = codec.id;
1641 send_codec_spec.cng_plfreq = cng_plfreq;
1642 break;
1643 }
1644 }
1645
1646 // Latch in the new state.
1647 send_codec_spec_ = std::move(send_codec_spec);
1648 }
1649
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001650 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001651 for (const auto& ch : send_streams_) {
skvlade0d46372016-04-07 22:59:22 -07001652 if (!SetSendCodecs(ch.second->channel(), ch.second->rtp_parameters())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001653 return false;
1654 }
1655 }
1656
solenberg72e29d22016-03-08 06:35:16 -08001657 // Set nack status on receive channels.
1658 if (!send_streams_.empty()) {
1659 for (const auto& kv : recv_streams_) {
1660 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1661 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001662 }
solenberg0a617e22015-10-20 15:49:38 -07001663
stefanba4c0e42016-02-04 04:12:24 -08001664 // Check if the transport cc feedback has changed on the preferred send codec,
1665 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001666 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1667 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1668 "codec has changed.";
1669 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1670 for (auto& kv : recv_streams_) {
1671 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1672 }
1673 }
1674
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07001675 send_codecs_ = codecs;
solenberg72e29d22016-03-08 06:35:16 -08001676 return true;
1677}
1678
1679// Apply current codec settings to a single voe::Channel used for sending.
skvlade0d46372016-04-07 22:59:22 -07001680bool WebRtcVoiceMediaChannel::SetSendCodecs(
1681 int channel,
1682 const webrtc::RtpParameters& rtp_parameters) {
solenberg72e29d22016-03-08 06:35:16 -08001683 // Disable VAD, FEC, and RED unless we know the other side wants them.
1684 engine()->voe()->codec()->SetVADStatus(channel, false);
1685 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1686 engine()->voe()->rtp()->SetREDStatus(channel, false);
1687 engine()->voe()->codec()->SetFECStatus(channel, false);
1688
1689 if (send_codec_spec_.red_payload_type != -1) {
1690 // Enable redundant encoding of the specified codec. Treat any
1691 // failure as a fatal internal error.
1692 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1693 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1694 send_codec_spec_.red_payload_type) == -1) {
1695 LOG_RTCERR3(SetREDStatus, channel, true,
1696 send_codec_spec_.red_payload_type);
1697 return false;
1698 }
1699 }
1700
1701 SetNack(channel, send_codec_spec_.nack_enabled);
1702
1703 // Set the codec immediately, since SetVADStatus() depends on whether
1704 // the current codec is mono or stereo.
1705 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1706 return false;
1707 }
1708
1709 // FEC should be enabled after SetSendCodec.
1710 if (send_codec_spec_.enable_codec_fec) {
1711 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1712 << channel;
1713 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1714 // Enable codec internal FEC. Treat any failure as fatal internal error.
1715 LOG_RTCERR2(SetFECStatus, channel, true);
1716 return false;
1717 }
1718 }
1719
1720 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1721 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1722 // send codec has to be Opus.
1723
1724 // Set Opus internal DTX.
1725 LOG(LS_INFO) << "Attempt to "
1726 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1727 << " Opus DTX on channel "
1728 << channel;
1729 if (engine()->voe()->codec()->SetOpusDtx(channel,
1730 send_codec_spec_.enable_opus_dtx)) {
1731 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1732 return false;
1733 }
1734
1735 // If opus_max_playback_rate <= 0, the default maximum playback rate
1736 // (48 kHz) will be used.
1737 if (send_codec_spec_.opus_max_playback_rate > 0) {
1738 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1739 << send_codec_spec_.opus_max_playback_rate
1740 << " Hz on channel "
1741 << channel;
1742 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1743 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1744 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1745 send_codec_spec_.opus_max_playback_rate);
1746 return false;
stefanba4c0e42016-02-04 04:12:24 -08001747 }
1748 }
1749 }
skvlade0d46372016-04-07 22:59:22 -07001750 // TODO(solenberg): SetSendBitrate() yields another call to SetSendCodec().
1751 // Check if it is possible to fuse with the previous call in this function.
1752 SetChannelParameters(channel, rtp_parameters);
solenberg72e29d22016-03-08 06:35:16 -08001753
1754 // Set the CN payloadtype and the VAD status.
1755 if (send_codec_spec_.cng_payload_type != -1) {
1756 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1757 if (send_codec_spec_.cng_plfreq != 8000) {
1758 webrtc::PayloadFrequencies cn_freq;
1759 switch (send_codec_spec_.cng_plfreq) {
1760 case 16000:
1761 cn_freq = webrtc::kFreq16000Hz;
1762 break;
1763 case 32000:
1764 cn_freq = webrtc::kFreq32000Hz;
1765 break;
1766 default:
1767 RTC_NOTREACHED();
1768 return false;
1769 }
1770 if (engine()->voe()->codec()->SetSendCNPayloadType(
1771 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1772 LOG_RTCERR3(SetSendCNPayloadType, channel,
1773 send_codec_spec_.cng_payload_type, cn_freq);
1774 // TODO(ajm): This failure condition will be removed from VoE.
1775 // Restore the return here when we update to a new enough webrtc.
1776 //
1777 // Not returning false because the SetSendCNPayloadType will fail if
1778 // the channel is already sending.
1779 // This can happen if the remote description is applied twice, for
1780 // example in the case of ROAP on top of JSEP, where both side will
1781 // send the offer.
1782 }
1783 }
1784
1785 // Only turn on VAD if we have a CN payload type that matches the
1786 // clockrate for the codec we are going to use.
1787 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1788 send_codec_spec_.codec_inst.channels == 1) {
1789 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1790 // interaction between VAD and Opus FEC.
1791 LOG(LS_INFO) << "Enabling VAD";
1792 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1793 LOG_RTCERR2(SetVADStatus, channel, true);
1794 return false;
1795 }
1796 }
1797 }
solenberg0a617e22015-10-20 15:49:38 -07001798 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001799}
1800
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001801void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001803 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1805 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001806 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1808 }
1809}
1810
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001812 int channel, const webrtc::CodecInst& send_codec) {
1813 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1814 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1815
solenberg72e29d22016-03-08 06:35:16 -08001816 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001817 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1818 (send_codec == current_codec)) {
1819 // Codec is already configured, we can return without setting it again.
1820 return true;
1821 }
1822
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001823 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1824 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825 return false;
1826 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return true;
1828}
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1831 desired_playout_ = playout;
1832 return ChangePlayout(desired_playout_);
1833}
1834
1835bool WebRtcVoiceMediaChannel::PausePlayout() {
1836 return ChangePlayout(false);
1837}
1838
1839bool WebRtcVoiceMediaChannel::ResumePlayout() {
1840 return ChangePlayout(desired_playout_);
1841}
1842
1843bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001844 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001845 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 if (playout_ == playout) {
1847 return true;
1848 }
1849
solenberg7add0582015-11-20 09:59:34 -08001850 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001851 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001852 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001853 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001854 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001855 }
1856 }
solenberg1ac56142015-10-13 03:58:19 -07001857 playout_ = playout;
1858 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859}
1860
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001861void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001862 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001863 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001864 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 }
1866
solenbergd53a3f92016-04-14 13:56:37 -07001867 // Apply channel specific options, and initialize the ADM for recording (this
1868 // may take time on some platforms, e.g. Android).
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001869 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001870 engine()->ApplyOptions(options_);
solenbergd53a3f92016-04-14 13:56:37 -07001871
1872 // InitRecording() may return an error if the ADM is already recording.
1873 if (!engine()->adm()->RecordingIsInitialized() &&
1874 !engine()->adm()->Recording()) {
1875 if (engine()->adm()->InitRecording() != 0) {
1876 LOG(LS_WARNING) << "Failed to initialize recording";
1877 }
1878 }
solenberg63b34542015-09-29 06:06:31 -07001879 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001881 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001882 for (auto& kv : send_streams_) {
1883 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001885
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001886 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887}
1888
Peter Boström0c4e06b2015-10-07 12:23:21 +02001889bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1890 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001891 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001892 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001893 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001894 // TODO(solenberg): The state change should be fully rolled back if any one of
1895 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001896 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001897 return false;
1898 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001899 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001900 return false;
1901 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001902 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001903 return SetOptions(*options);
1904 }
1905 return true;
1906}
1907
solenberg0a617e22015-10-20 15:49:38 -07001908int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1909 int id = engine()->CreateVoEChannel();
1910 if (id == -1) {
1911 LOG_RTCERR0(CreateVoEChannel);
1912 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001913 }
solenberg0a617e22015-10-20 15:49:38 -07001914 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1915 LOG_RTCERR2(RegisterExternalTransport, id, this);
1916 engine()->voe()->base()->DeleteChannel(id);
1917 return -1;
1918 }
1919 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001920}
1921
solenberg7add0582015-11-20 09:59:34 -08001922bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001923 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1924 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1925 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001926 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1927 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 return false;
1929 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001930 return true;
1931}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001932
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001933bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001934 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001935 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001936 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1937
1938 uint32_t ssrc = sp.first_ssrc();
1939 RTC_DCHECK(0 != ssrc);
1940
1941 if (GetSendChannelId(ssrc) != -1) {
1942 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001943 return false;
1944 }
1945
solenberg0a617e22015-10-20 15:49:38 -07001946 // Create a new channel for sending audio data.
1947 int channel = CreateVoEChannel();
1948 if (channel == -1) {
1949 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001950 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001951
solenbergc96df772015-10-21 13:01:53 -07001952 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001953 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001954 webrtc::AudioTransport* audio_transport =
1955 engine()->voe()->base()->audio_transport();
skvlade0d46372016-04-07 22:59:22 -07001956 WebRtcAudioSendStream* stream = new WebRtcAudioSendStream(
1957 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_);
1958 send_streams_.insert(std::make_pair(ssrc, stream));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001959
solenberg0a617e22015-10-20 15:49:38 -07001960 // Set the current codecs to be used for the new channel. We need to do this
1961 // after adding the channel to send_channels_, because of how max bitrate is
1962 // currently being configured by SetSendCodec().
skvlade0d46372016-04-07 22:59:22 -07001963 if (HasSendCodec() && !SetSendCodecs(channel, stream->rtp_parameters())) {
solenberg0a617e22015-10-20 15:49:38 -07001964 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001965 return false;
1966 }
1967
1968 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001969 // the first send channel make sure that all the receive channels are updated
1970 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001971 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001972 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001973 for (const auto& stream : recv_streams_) {
1974 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001975 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001976 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001977 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001978 }
solenberg0a617e22015-10-20 15:49:38 -07001979 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1980 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1981 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001982 }
1983 }
1984
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001985 send_streams_[ssrc]->SetSend(send_);
1986 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001987}
1988
Peter Boström0c4e06b2015-10-07 12:23:21 +02001989bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001990 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001991 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001992 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1993
solenbergc96df772015-10-21 13:01:53 -07001994 auto it = send_streams_.find(ssrc);
1995 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001996 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1997 << " which doesn't exist.";
1998 return false;
1999 }
2000
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002001 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002002
solenberg7add0582015-11-20 09:59:34 -08002003 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002004 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07002005 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2006 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08002007 delete it->second;
2008 send_streams_.erase(it);
2009 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07002010 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002011 }
solenbergc96df772015-10-21 13:01:53 -07002012 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002013 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07002014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 return true;
2016}
2017
2018bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002019 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002020 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002021 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2022
solenberg0b675462015-10-09 01:37:09 -07002023 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002024 return false;
2025 }
2026
solenberg7add0582015-11-20 09:59:34 -08002027 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002028 if (ssrc == 0) {
2029 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2030 return false;
2031 }
2032
solenberg1ac56142015-10-13 03:58:19 -07002033 // Remove the default receive stream if one had been created with this ssrc;
2034 // we'll recreate it then.
2035 if (IsDefaultRecvStream(ssrc)) {
2036 RemoveRecvStream(ssrc);
2037 }
solenberg0b675462015-10-09 01:37:09 -07002038
solenberg7add0582015-11-20 09:59:34 -08002039 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002040 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041 return false;
2042 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002043
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002045 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 return false;
2048 }
Minyue2013aec2015-05-13 14:14:42 +02002049
solenberg1ac56142015-10-13 03:58:19 -07002050 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002051 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2052 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2053 voe_codec.pltype = -1;
2054 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2055 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2056 DeleteVoEChannel(channel);
2057 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058 }
2059 }
2060
solenberg1ac56142015-10-13 03:58:19 -07002061 // Only enable those configured for this channel.
2062 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002063 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002064 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002065 voe_codec.pltype = codec.id;
2066 if (engine()->voe()->codec()->SetRecPayloadType(
2067 channel, voe_codec) == -1) {
2068 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002069 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002070 return false;
2071 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002072 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073 }
solenberg8fb30c32015-10-13 03:06:58 -07002074
solenberg7add0582015-11-20 09:59:34 -08002075 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2076 if (send_channel != -1) {
2077 // Associate receive channel with first send channel (so the receive channel
2078 // can obtain RTT from the send channel)
2079 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2080 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2081 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002082 }
2083
stefanba4c0e42016-02-04 04:12:24 -08002084 recv_streams_.insert(std::make_pair(
2085 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002086 recv_transport_cc_enabled_,
2087 sp.sync_label, recv_rtp_extensions_,
2088 call_)));
solenberg7add0582015-11-20 09:59:34 -08002089
solenberg72e29d22016-03-08 06:35:16 -08002090 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002091 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002092
solenberg1ac56142015-10-13 03:58:19 -07002093 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094}
2095
Peter Boström0c4e06b2015-10-07 12:23:21 +02002096bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002097 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002098 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002099 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2100
solenberg7add0582015-11-20 09:59:34 -08002101 const auto it = recv_streams_.find(ssrc);
2102 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002103 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2104 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002105 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002106 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107
solenberg1ac56142015-10-13 03:58:19 -07002108 // Deregister default channel, if that's the one being destroyed.
2109 if (IsDefaultRecvStream(ssrc)) {
2110 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002111 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002112
solenberg7add0582015-11-20 09:59:34 -08002113 const int channel = it->second->channel();
2114
2115 // Clean up and delete the receive stream+channel.
2116 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002117 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002118 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002119 delete it->second;
2120 recv_streams_.erase(it);
2121 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122}
2123
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002124bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2125 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002126 auto it = send_streams_.find(ssrc);
2127 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002128 if (source) {
2129 // Return an error if trying to set a valid source with an invalid ssrc.
2130 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002131 return false;
2132 }
2133
2134 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002135 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002136 }
2137
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002138 if (source) {
2139 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002140 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002141 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002142 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 return true;
2145}
2146
2147bool WebRtcVoiceMediaChannel::GetActiveStreams(
2148 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002149 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002151 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002152 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002154 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002155 }
2156 }
2157 return true;
2158}
2159
2160int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002161 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002162 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002163 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002164 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 }
2166 return highest;
2167}
2168
2169int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2170 int ret;
2171 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2172 // In case of error, log the info and continue
2173 LOG_RTCERR0(TimeSinceLastTyping);
2174 ret = -1;
2175 } else {
2176 ret *= 1000; // We return ms, webrtc returns seconds.
2177 }
2178 return ret;
2179}
2180
2181void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2182 int cost_per_typing, int reporting_threshold, int penalty_decay,
2183 int type_event_delay) {
2184 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2185 time_window, cost_per_typing,
2186 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2187 // In case of error, log the info and continue
2188 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2189 cost_per_typing, reporting_threshold, penalty_decay,
2190 type_event_delay);
2191 }
2192}
2193
solenberg4bac9c52015-10-09 02:32:53 -07002194bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002195 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002196 if (ssrc == 0) {
2197 default_recv_volume_ = volume;
2198 if (default_recv_ssrc_ == -1) {
2199 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 }
solenberg1ac56142015-10-13 03:58:19 -07002201 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2202 }
2203 int ch_id = GetReceiveChannelId(ssrc);
2204 if (ch_id < 0) {
2205 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2206 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 }
2208
solenberg1ac56142015-10-13 03:58:19 -07002209 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2210 volume)) {
2211 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2212 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 }
solenberg1ac56142015-10-13 03:58:19 -07002214 LOG(LS_INFO) << "SetOutputVolume to " << volume
2215 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216 return true;
2217}
2218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002220 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221}
2222
solenberg1d63dd02015-12-02 12:35:09 -08002223bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2224 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002225 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002226 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2227 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 return false;
2229 }
2230
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002231 // Figure out which WebRtcAudioSendStream to send the event on.
2232 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2233 if (it == send_streams_.end()) {
2234 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002235 return false;
2236 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002237 if (event < kMinTelephoneEventCode ||
2238 event > kMaxTelephoneEventCode) {
2239 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002240 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002242 if (duration < kMinTelephoneEventDuration ||
2243 duration > kMaxTelephoneEventDuration) {
2244 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2245 return false;
2246 }
2247 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248}
2249
wu@webrtc.orga9890802013-12-13 00:21:03 +00002250void WebRtcVoiceMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002251 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002252 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002253
solenberg1ac56142015-10-13 03:58:19 -07002254 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002255 if (!GetRtpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg1ac56142015-10-13 03:58:19 -07002256 return;
2257 }
2258
solenberg7e63ef02015-11-20 00:19:43 -08002259 // If we don't have a default channel, and the SSRC is unknown, create a
2260 // default channel.
2261 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002262 StreamParams sp;
2263 sp.ssrcs.push_back(ssrc);
2264 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2265 if (!AddRecvStream(sp)) {
2266 LOG(LS_WARNING) << "Could not create default receive stream.";
2267 return;
2268 }
2269 default_recv_ssrc_ = ssrc;
2270 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002271 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002272 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002273 new ProxySink(default_sink_.get()));
2274 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2275 }
solenberg1ac56142015-10-13 03:58:19 -07002276 }
2277
2278 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002279 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2280 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002281 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2282 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002283 packet->cdata(), packet->size(), webrtc_packet_time);
solenberg1ac56142015-10-13 03:58:19 -07002284 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002285 // If the SSRC is unknown here, route it to the default channel, if we have
2286 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2287 if (default_recv_ssrc_ == -1) {
2288 return;
2289 } else {
2290 ssrc = default_recv_ssrc_;
2291 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292 }
2293
solenberg1ac56142015-10-13 03:58:19 -07002294 // Find the channel to send this packet to. It must exist since webrtc::Call
2295 // was able to demux the packet.
2296 int channel = GetReceiveChannelId(ssrc);
2297 RTC_DCHECK(channel != -1);
2298
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002299 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002300 engine()->voe()->network()->ReceivedRTPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002301 channel, packet->cdata(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302}
2303
wu@webrtc.orga9890802013-12-13 00:21:03 +00002304void WebRtcVoiceMediaChannel::OnRtcpReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002305 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002306 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002307
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002308 // Forward packet to Call as well.
2309 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2310 packet_time.not_before);
2311 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002312 packet->cdata(), packet->size(), webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002313
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002314 // Sending channels need all RTCP packets with feedback information.
2315 // Even sender reports can contain attached report blocks.
2316 // Receiving channels need sender reports in order to create
2317 // correct receiver reports.
2318 int type = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002319 if (!GetRtcpType(packet->cdata(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002320 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2321 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 }
2323
solenberg0b675462015-10-09 01:37:09 -07002324 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002325 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002326 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002327 if (!GetRtcpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg0b675462015-10-09 01:37:09 -07002328 return;
2329 }
2330 int recv_channel_id = GetReceiveChannelId(ssrc);
2331 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002332 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002333 recv_channel_id, packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002334 }
2335 }
2336
2337 // SR may continue RR and any RR entry may correspond to any one of the send
2338 // channels. So all RTCP packets must be forwarded all send channels. VoE
2339 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002340 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002341 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002342 ch.second->channel(), packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002343 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344}
2345
Honghai Zhangcc411c02016-03-29 17:27:21 -07002346void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2347 const std::string& transport_name,
Honghai Zhang0e533ef2016-04-19 15:41:36 -07002348 const rtc::NetworkRoute& network_route) {
2349 call_->OnNetworkRouteChanged(transport_name, network_route);
Honghai Zhangcc411c02016-03-29 17:27:21 -07002350}
2351
Peter Boström0c4e06b2015-10-07 12:23:21 +02002352bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002353 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002354 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002355 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2357 return false;
2358 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002359 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2360 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002361 return false;
2362 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002363 // We set the AGC to mute state only when all the channels are muted.
2364 // This implementation is not ideal, instead we should signal the AGC when
2365 // the mic channel is muted/unmuted. We can't do it today because there
2366 // is no good way to know which stream is mapping to the mic channel.
2367 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002368 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002369 if (!all_muted) {
2370 break;
2371 }
2372 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002373 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002374 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002375 return false;
2376 }
2377 }
2378
2379 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002380 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002381 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002382 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 return true;
2384}
2385
skvlade0d46372016-04-07 22:59:22 -07002386bool WebRtcVoiceMediaChannel::SetSendBitrate(int bps) {
2387 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrate.";
2388 send_bitrate_bps_ = bps;
2389
2390 for (const auto& kv : send_streams_) {
2391 if (!SetChannelParameters(kv.second->channel(),
2392 kv.second->rtp_parameters())) {
2393 return false;
2394 }
2395 }
2396 return true;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002397}
2398
skvlade0d46372016-04-07 22:59:22 -07002399bool WebRtcVoiceMediaChannel::SetChannelParameters(
2400 int channel,
2401 const webrtc::RtpParameters& parameters) {
2402 RTC_CHECK_EQ(1UL, parameters.encodings.size());
Taylor Brandstetter0cd086b2016-04-20 16:23:10 -07002403 // TODO(deadbeef): Handle setting parameters with a list of codecs in a
2404 // different order (which should change the send codec).
skvlade0d46372016-04-07 22:59:22 -07002405 return SetSendBitrate(
2406 channel,
2407 MinPositive(send_bitrate_bps_, parameters.encodings[0].max_bitrate_bps));
2408}
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002409
skvlade0d46372016-04-07 22:59:22 -07002410bool WebRtcVoiceMediaChannel::SetSendBitrate(int channel, int bps) {
2411 // Bitrate is auto by default.
2412 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2413 // SetMaxSendBandwith(0), the second call removes the previous limit.
2414 if (bps <= 0)
2415 return true;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002416
solenberg72e29d22016-03-08 06:35:16 -08002417 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002418 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002419 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002420 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002421 }
2422
solenberg72e29d22016-03-08 06:35:16 -08002423 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002424 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425
2426 if (is_multi_rate) {
2427 // If codec is multi-rate then just set the bitrate.
2428 codec.rate = bps;
skvlade0d46372016-04-07 22:59:22 -07002429 if (!SetSendCodec(channel, codec)) {
2430 LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate "
2431 << bps << " bps.";
2432 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433 }
2434 return true;
2435 } else {
2436 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2437 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2438 // fixed bitrate then ignore.
2439 if (bps < codec.rate) {
2440 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2441 << " to bitrate " << bps << " bps"
2442 << ", requires at least " << codec.rate << " bps.";
2443 return false;
2444 }
2445 return true;
2446 }
2447}
2448
skvlad7a43d252016-03-22 15:32:27 -07002449void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2450 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2451 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2452 call_->SignalChannelNetworkState(
2453 webrtc::MediaType::AUDIO,
2454 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2455}
2456
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002457bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002458 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002459 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002460 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002461
solenberg85a04962015-10-27 03:35:21 -07002462 // Get SSRC and stats for each sender.
2463 RTC_DCHECK(info->senders.size() == 0);
2464 for (const auto& stream : send_streams_) {
2465 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002466 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002467 sinfo.add_ssrc(stats.local_ssrc);
2468 sinfo.bytes_sent = stats.bytes_sent;
2469 sinfo.packets_sent = stats.packets_sent;
2470 sinfo.packets_lost = stats.packets_lost;
2471 sinfo.fraction_lost = stats.fraction_lost;
2472 sinfo.codec_name = stats.codec_name;
2473 sinfo.ext_seqnum = stats.ext_seqnum;
2474 sinfo.jitter_ms = stats.jitter_ms;
2475 sinfo.rtt_ms = stats.rtt_ms;
2476 sinfo.audio_level = stats.audio_level;
2477 sinfo.aec_quality_min = stats.aec_quality_min;
2478 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2479 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2480 sinfo.echo_return_loss = stats.echo_return_loss;
2481 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002482 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002483 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484 }
2485
solenberg85a04962015-10-27 03:35:21 -07002486 // Get SSRC and stats for each receiver.
2487 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002488 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002489 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2490 VoiceReceiverInfo rinfo;
2491 rinfo.add_ssrc(stats.remote_ssrc);
2492 rinfo.bytes_rcvd = stats.bytes_rcvd;
2493 rinfo.packets_rcvd = stats.packets_rcvd;
2494 rinfo.packets_lost = stats.packets_lost;
2495 rinfo.fraction_lost = stats.fraction_lost;
2496 rinfo.codec_name = stats.codec_name;
2497 rinfo.ext_seqnum = stats.ext_seqnum;
2498 rinfo.jitter_ms = stats.jitter_ms;
2499 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2500 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2501 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2502 rinfo.audio_level = stats.audio_level;
2503 rinfo.expand_rate = stats.expand_rate;
2504 rinfo.speech_expand_rate = stats.speech_expand_rate;
2505 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2506 rinfo.accelerate_rate = stats.accelerate_rate;
2507 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2508 rinfo.decoding_calls_to_silence_generator =
2509 stats.decoding_calls_to_silence_generator;
2510 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2511 rinfo.decoding_normal = stats.decoding_normal;
2512 rinfo.decoding_plc = stats.decoding_plc;
2513 rinfo.decoding_cng = stats.decoding_cng;
2514 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2515 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2516 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517 }
2518
2519 return true;
2520}
2521
Tommif888bb52015-12-12 01:37:01 +01002522void WebRtcVoiceMediaChannel::SetRawAudioSink(
2523 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002524 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002525 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002526 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2527 << " " << (sink ? "(ptr)" : "NULL");
2528 if (ssrc == 0) {
2529 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002530 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002531 sink ? new ProxySink(sink.get()) : nullptr);
2532 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2533 }
2534 default_sink_ = std::move(sink);
2535 return;
2536 }
Tommif888bb52015-12-12 01:37:01 +01002537 const auto it = recv_streams_.find(ssrc);
2538 if (it == recv_streams_.end()) {
2539 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2540 return;
2541 }
deadbeef2d110be2016-01-13 12:00:26 -08002542 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002543}
2544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002546 unsigned int ulevel = 0;
2547 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2549}
2550
Peter Boström0c4e06b2015-10-07 12:23:21 +02002551int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002552 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002553 const auto it = recv_streams_.find(ssrc);
2554 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002555 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002556 }
solenberg1ac56142015-10-13 03:58:19 -07002557 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558}
2559
Peter Boström0c4e06b2015-10-07 12:23:21 +02002560int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002561 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002562 const auto it = send_streams_.find(ssrc);
2563 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002564 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002565 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002566 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002567}
2568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2570 if (playout) {
2571 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2572 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2573 LOG_RTCERR1(StartPlayout, channel);
2574 return false;
2575 }
2576 } else {
2577 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2578 engine()->voe()->base()->StopPlayout(channel);
2579 }
2580 return true;
2581}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002582} // namespace cricket
2583
2584#endif // HAVE_WEBRTC_VOICE