blob: 46119311bce328c4b47f5b139c3e776855bee855 [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"
kjellandera96e2d72016-02-04 23:52:28 -080032#include "webrtc/media/base/audioframe.h"
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -080033#include "webrtc/media/base/audiosource.h"
kjellanderf4752772016-03-02 05:42:30 -080034#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080035#include "webrtc/media/base/streamparams.h"
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010036#include "webrtc/media/engine/webrtcmediaengine.h"
37#include "webrtc/media/engine/webrtcvoe.h"
solenberg26c8c912015-11-27 04:00:25 -080038#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000039#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010040#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080041#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070044namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
solenbergbd138382015-11-20 16:08:07 -080046const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
47 webrtc::kTraceWarning | webrtc::kTraceError |
48 webrtc::kTraceCritical;
49const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
50 webrtc::kTraceInfo;
51
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052// On Windows Vista and newer, Microsoft introduced the concept of "Default
53// Communications Device". This means that there are two types of default
54// devices (old Wave Audio style default and Default Communications Device).
55//
56// On Windows systems which only support Wave Audio style default, uses either
57// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070059const int kDefaultAudioDeviceId = -1;
solenberg8ad582d2016-03-16 09:34:56 -070060#elif !defined(WEBRTC_IOS)
solenbergd97ec302015-10-07 01:40:33 -070061const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062#endif
63
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064// Parameter used for NACK.
65// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070066const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000067
68// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000069// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000070
71// Recommended bitrates:
72// 8-12 kb/s for NB speech,
73// 16-20 kb/s for WB speech,
74// 28-40 kb/s for FB speech,
75// 48-64 kb/s for FB mono music, and
76// 64-128 kb/s for FB stereo music.
77// The current implementation applies the following values to mono signals,
78// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070079const int kOpusBitrateNb = 12000;
80const int kOpusBitrateWb = 20000;
81const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000082
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000083// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -070084const int kOpusMinBitrate = 6000;
85const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000086
wu@webrtc.orgde305012013-10-31 15:40:38 +000087// Default audio dscp value.
88// See http://tools.ietf.org/html/rfc2474 for details.
89// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -070090const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000091
Fredrik Solenbergb5727682015-12-04 15:22:19 +010092// Constants from voice_engine_defines.h.
93const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
94const int kMaxTelephoneEventCode = 255;
95const int kMinTelephoneEventDuration = 100;
96const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
97
solenberg31642aa2016-03-14 08:00:37 -070098const int kMinPayloadType = 0;
99const int kMaxPayloadType = 127;
100
deadbeef884f5852016-01-15 09:20:04 -0800101class ProxySink : public webrtc::AudioSinkInterface {
102 public:
103 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
104
105 void OnData(const Data& audio) override { sink_->OnData(audio); }
106
107 private:
108 webrtc::AudioSinkInterface* sink_;
109};
110
solenberg0b675462015-10-09 01:37:09 -0700111bool ValidateStreamParams(const StreamParams& sp) {
112 if (sp.ssrcs.empty()) {
113 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
114 return false;
115 }
116 if (sp.ssrcs.size() > 1) {
117 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
118 return false;
119 }
120 return true;
121}
122
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700124std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 std::stringstream ss;
126 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
127 << " (" << codec.id << ")";
128 return ss.str();
129}
Minyue Li7100dcd2015-03-27 05:05:59 +0100130
solenbergd97ec302015-10-07 01:40:33 -0700131std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 std::stringstream ss;
133 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
134 << " (" << codec.pltype << ")";
135 return ss.str();
136}
137
solenbergd97ec302015-10-07 01:40:33 -0700138bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100139 return (_stricmp(codec.name.c_str(), ref_name) == 0);
140}
141
solenbergd97ec302015-10-07 01:40:33 -0700142bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100143 return (_stricmp(codec.plname, ref_name) == 0);
144}
145
solenbergd97ec302015-10-07 01:40:33 -0700146bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800147 const AudioCodec& codec,
148 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200149 for (const AudioCodec& c : codecs) {
150 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200152 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153 }
154 return true;
155 }
156 }
157 return false;
158}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000159
solenberg0b675462015-10-09 01:37:09 -0700160bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
161 if (codecs.empty()) {
162 return true;
163 }
164 std::vector<int> payload_types;
165 for (const AudioCodec& codec : codecs) {
166 payload_types.push_back(codec.id);
167 }
168 std::sort(payload_types.begin(), payload_types.end());
169 auto it = std::unique(payload_types.begin(), payload_types.end());
170 return it == payload_types.end();
171}
172
Minyue Li7100dcd2015-03-27 05:05:59 +0100173// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800174bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100175 int value;
176 return codec.GetParam(feature, &value) && value == 1;
177}
178
179// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
180// otherwise. If the value (either from params or codec.bitrate) <=0, use the
181// default configuration. If the value is beyond feasible bit rate of Opus,
182// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700183int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100184 int bitrate = 0;
185 bool use_param = true;
186 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
187 bitrate = codec.bitrate;
188 use_param = false;
189 }
190 if (bitrate <= 0) {
191 if (max_playback_rate <= 8000) {
192 bitrate = kOpusBitrateNb;
193 } else if (max_playback_rate <= 16000) {
194 bitrate = kOpusBitrateWb;
195 } else {
196 bitrate = kOpusBitrateFb;
197 }
198
199 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
200 bitrate *= 2;
201 }
202 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
203 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
204 std::string rate_source =
205 use_param ? "Codec parameter \"maxaveragebitrate\"" :
206 "Supplied Opus bitrate";
207 LOG(LS_WARNING) << rate_source
208 << " is invalid and is replaced by: "
209 << bitrate;
210 }
211 return bitrate;
212}
213
214// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
215// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700216int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100217 int value;
218 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
219 return value;
220 }
221 return kOpusDefaultMaxPlaybackRate;
222}
223
solenbergd97ec302015-10-07 01:40:33 -0700224void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100225 bool* enable_codec_fec, int* max_playback_rate,
226 bool* enable_codec_dtx) {
227 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
228 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
229 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
230
231 // If OPUS, change what we send according to the "stereo" codec
232 // parameter, and not the "channels" parameter. We set
233 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
234 // the bitrate is not specified, i.e. is <= zero, we set it to the
235 // appropriate default value for mono or stereo Opus.
236
237 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
238 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
239}
240
solenberg566ef242015-11-06 15:34:49 -0800241webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
242 webrtc::AudioState::Config config;
243 config.voice_engine = voe_wrapper->engine();
244 return config;
245}
246
solenberg26c8c912015-11-27 04:00:25 -0800247class WebRtcVoiceCodecs final {
248 public:
249 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
250 // list and add a test which verifies VoE supports the listed codecs.
251 static std::vector<AudioCodec> SupportedCodecs() {
solenberg26c8c912015-11-27 04:00:25 -0800252 std::vector<AudioCodec> result;
deadbeef67cf2c12016-04-13 10:07:16 -0700253 // Iterate first over our preferred codecs list, so that the results are
254 // added in order of preference.
255 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
256 const CodecPref* pref = &kCodecPrefs[i];
257 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
258 // Change the sample rate of G722 to 8000 to match SDP.
259 MaybeFixupG722(&voe_codec, 8000);
260 // Skip uncompressed formats.
261 if (IsCodec(voe_codec, kL16CodecName)) {
262 continue;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000263 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000264
deadbeef67cf2c12016-04-13 10:07:16 -0700265 if (!IsCodec(voe_codec, pref->name) ||
266 pref->clockrate != voe_codec.plfreq ||
267 pref->channels != voe_codec.channels) {
268 // Not a match.
269 continue;
270 }
271
272 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
273 voe_codec.rate, voe_codec.channels);
274 LOG(LS_INFO) << "Adding supported codec: " << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100275 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000276 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000277 codec.bitrate = 0;
278 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100279 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000280 // Only add fmtp parameters that differ from the spec.
281 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
282 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000283 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000284 }
285 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
286 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000287 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000288 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000289 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800290 codec.AddFeedbackParam(
291 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000292
293 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000294 // when they can be set to values other than the default.
295 }
solenberg26c8c912015-11-27 04:00:25 -0800296 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000297 }
298 }
solenberg26c8c912015-11-27 04:00:25 -0800299 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000300 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000301
solenberg26c8c912015-11-27 04:00:25 -0800302 static bool ToCodecInst(const AudioCodec& in,
303 webrtc::CodecInst* out) {
304 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
305 // Change the sample rate of G722 to 8000 to match SDP.
306 MaybeFixupG722(&voe_codec, 8000);
307 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
deadbeef67cf2c12016-04-13 10:07:16 -0700308 voe_codec.rate, voe_codec.channels);
solenberg26c8c912015-11-27 04:00:25 -0800309 bool multi_rate = IsCodecMultiRate(voe_codec);
310 // Allow arbitrary rates for ISAC to be specified.
311 if (multi_rate) {
312 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
313 codec.bitrate = 0;
314 }
315 if (codec.Matches(in)) {
316 if (out) {
317 // Fixup the payload type.
318 voe_codec.pltype = in.id;
319
320 // Set bitrate if specified.
321 if (multi_rate && in.bitrate != 0) {
322 voe_codec.rate = in.bitrate;
323 }
324
325 // Reset G722 sample rate to 16000 to match WebRTC.
326 MaybeFixupG722(&voe_codec, 16000);
327
328 // Apply codec-specific settings.
329 if (IsCodec(codec, kIsacCodecName)) {
330 // If ISAC and an explicit bitrate is not specified,
331 // enable auto bitrate adjustment.
332 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
333 }
334 *out = voe_codec;
335 }
336 return true;
337 }
338 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000339 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000340 }
solenberg26c8c912015-11-27 04:00:25 -0800341
342 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
343 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
344 if (IsCodec(codec, kCodecPrefs[i].name) &&
345 kCodecPrefs[i].clockrate == codec.plfreq) {
346 return kCodecPrefs[i].is_multi_rate;
347 }
348 }
349 return false;
350 }
351
352 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
353 // codec pacsize if it's valid, or we will pick the next smallest value we
354 // support.
355 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
356 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
357 for (const CodecPref& codec_pref : kCodecPrefs) {
358 if ((IsCodec(*codec, codec_pref.name) &&
359 codec_pref.clockrate == codec->plfreq) ||
360 IsCodec(*codec, kG722CodecName)) {
361 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
362 if (packet_size_ms) {
363 // Convert unit from milli-seconds to samples.
364 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
365 return true;
366 }
367 }
368 }
369 return false;
370 }
371
stefanba4c0e42016-02-04 04:12:24 -0800372 static const AudioCodec* GetPreferredCodec(
373 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800374 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800375 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800376 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800377 RTC_DCHECK(red_payload_type);
378 // Select the preferred send codec (the first non-telephone-event/CN codec).
379 for (const AudioCodec& codec : codecs) {
380 *red_payload_type = -1;
381 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
382 // Skip telephone-event/CN codec, which will be handled later.
383 continue;
384 }
385
386 // We'll use the first codec in the list to actually send audio data.
387 // Be sure to use the payload type requested by the remote side.
388 // "red", for RED audio, is a special case where the actual codec to be
389 // used is specified in params.
390 const AudioCodec* found_codec = &codec;
391 if (IsCodec(*found_codec, kRedCodecName)) {
392 // Parse out the RED parameters. If we fail, just ignore RED;
393 // we don't support all possible params/usage scenarios.
394 *red_payload_type = codec.id;
395 found_codec = GetRedSendCodec(*found_codec, codecs);
396 if (!found_codec) {
397 continue;
398 }
399 }
400 // Ignore codecs we don't know about. The negotiation step should prevent
401 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800402 webrtc::CodecInst voe_codec = {0};
403 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800404 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
405 continue;
406 }
solenberg72e29d22016-03-08 06:35:16 -0800407 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800408 return found_codec;
409 }
410 return nullptr;
411 }
412
solenberg26c8c912015-11-27 04:00:25 -0800413 private:
414 static const int kMaxNumPacketSize = 6;
415 struct CodecPref {
416 const char* name;
417 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800418 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800419 int payload_type;
420 bool is_multi_rate;
421 int packet_sizes_ms[kMaxNumPacketSize];
422 };
423 // Note: keep the supported packet sizes in ascending order.
424 static const CodecPref kCodecPrefs[12];
425
426 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
427 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
428 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
429 if (packet_size_ms && packet_size_ms <= ptime_ms) {
430 selected_packet_size_ms = packet_size_ms;
431 }
432 }
433 return selected_packet_size_ms;
434 }
435
436 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
437 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
438 // codec.
439 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
440 if (IsCodec(*voe_codec, kG722CodecName)) {
441 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
442 // has changed, and this special case is no longer needed.
443 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
444 voe_codec->plfreq = new_plfreq;
445 }
446 }
stefanba4c0e42016-02-04 04:12:24 -0800447
448 static const AudioCodec* GetRedSendCodec(
449 const AudioCodec& red_codec,
450 const std::vector<AudioCodec>& all_codecs) {
451 // Get the RED encodings from the parameter with no name. This may
452 // change based on what is discussed on the Jingle list.
453 // The encoding parameter is of the form "a/b"; we only support where
454 // a == b. Verify this and parse out the value into red_pt.
455 // If the parameter value is absent (as it will be until we wire up the
456 // signaling of this message), use the second codec specified (i.e. the
457 // one after "red") as the encoding parameter.
458 int red_pt = -1;
459 std::string red_params;
460 CodecParameterMap::const_iterator it = red_codec.params.find("");
461 if (it != red_codec.params.end()) {
462 red_params = it->second;
463 std::vector<std::string> red_pts;
464 if (rtc::split(red_params, '/', &red_pts) != 2 ||
465 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
466 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
467 return nullptr;
468 }
469 } else if (red_codec.params.empty()) {
470 LOG(LS_WARNING) << "RED params not present, using defaults";
471 if (all_codecs.size() > 1) {
472 red_pt = all_codecs[1].id;
473 }
474 }
475
476 // Try to find red_pt in |codecs|.
477 for (const AudioCodec& codec : all_codecs) {
478 if (codec.id == red_pt) {
479 return &codec;
480 }
481 }
482 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
483 return nullptr;
484 }
solenberg26c8c912015-11-27 04:00:25 -0800485};
486
487const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
488 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
489 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
490 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
491 // G722 should be advertised as 8000 Hz because of the RFC "bug".
492 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
493 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
494 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
495 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
496 { kCnCodecName, 32000, 1, 106, false, { } },
497 { kCnCodecName, 16000, 1, 105, false, { } },
498 { kCnCodecName, 8000, 1, 13, false, { } },
499 { kRedCodecName, 8000, 1, 127, false, { } },
500 { kDtmfCodecName, 8000, 1, 126, false, { } },
501};
502} // namespace {
503
504bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
505 webrtc::CodecInst* out) {
506 return WebRtcVoiceCodecs::ToCodecInst(in, out);
507}
508
solenbergff976312016-03-30 23:28:51 -0700509WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm)
510 : WebRtcVoiceEngine(adm, new VoEWrapper()) {
511 audio_state_ = webrtc::AudioState::Create(MakeAudioStateConfig(voe()));
solenberg26c8c912015-11-27 04:00:25 -0800512}
513
solenbergff976312016-03-30 23:28:51 -0700514WebRtcVoiceEngine::WebRtcVoiceEngine(webrtc::AudioDeviceModule* adm,
515 VoEWrapper* voe_wrapper)
516 : adm_(adm), voe_wrapper_(voe_wrapper) {
solenberg26c8c912015-11-27 04:00:25 -0800517 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700518 LOG(LS_INFO) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
519 RTC_DCHECK(voe_wrapper);
solenberg26c8c912015-11-27 04:00:25 -0800520
521 signal_thread_checker_.DetachFromThread();
solenberg26c8c912015-11-27 04:00:25 -0800522
523 // Load our audio codec list.
solenbergff976312016-03-30 23:28:51 -0700524 LOG(LS_INFO) << "Supported codecs in order of preference:";
solenberg26c8c912015-11-27 04:00:25 -0800525 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
solenbergff976312016-03-30 23:28:51 -0700526 for (const AudioCodec& codec : codecs_) {
527 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000529
solenbergff976312016-03-30 23:28:51 -0700530 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531
solenbergff976312016-03-30 23:28:51 -0700532 // Temporarily turn logging level up for the Init() call.
533 webrtc::Trace::SetTraceCallback(this);
solenbergbd138382015-11-20 16:08:07 -0800534 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800535 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
solenbergff976312016-03-30 23:28:51 -0700536 RTC_CHECK_EQ(0, voe_wrapper_->base()->Init(adm_.get()));
solenbergbd138382015-11-20 16:08:07 -0800537 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000538
solenbergff976312016-03-30 23:28:51 -0700539 // No ADM supplied? Get the default one from VoE.
540 if (!adm_) {
541 adm_ = voe_wrapper_->base()->audio_device_module();
542 }
543 RTC_DCHECK(adm_);
544
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800546 // calling ApplyOptions or the default will be overwritten.
solenbergff976312016-03-30 23:28:51 -0700547 int error = voe_wrapper_->processing()->GetAgcConfig(default_agc_config_);
548 RTC_DCHECK_EQ(0, error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000549
solenberg0f7d2932016-01-15 01:40:39 -0800550 // Set default engine options.
551 {
552 AudioOptions options;
553 options.echo_cancellation = rtc::Optional<bool>(true);
554 options.auto_gain_control = rtc::Optional<bool>(true);
555 options.noise_suppression = rtc::Optional<bool>(true);
556 options.highpass_filter = rtc::Optional<bool>(true);
557 options.stereo_swapping = rtc::Optional<bool>(false);
558 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
559 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
560 options.typing_detection = rtc::Optional<bool>(true);
561 options.adjust_agc_delta = rtc::Optional<int>(0);
562 options.experimental_agc = rtc::Optional<bool>(false);
563 options.extended_filter_aec = rtc::Optional<bool>(false);
564 options.delay_agnostic_aec = rtc::Optional<bool>(false);
565 options.experimental_ns = rtc::Optional<bool>(false);
solenbergff976312016-03-30 23:28:51 -0700566 bool error = ApplyOptions(options);
567 RTC_DCHECK(error);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568 }
569
solenberg246b8172015-12-08 09:50:23 -0800570 SetDefaultDevices();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000571}
572
solenbergff976312016-03-30 23:28:51 -0700573WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800574 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700575 LOG(LS_INFO) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 StopAecDump();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000577 voe_wrapper_->base()->Terminate();
solenbergff976312016-03-30 23:28:51 -0700578 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000579}
580
solenberg566ef242015-11-06 15:34:49 -0800581rtc::scoped_refptr<webrtc::AudioState>
582 WebRtcVoiceEngine::GetAudioState() const {
583 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
584 return audio_state_;
585}
586
nisse51542be2016-02-12 02:27:06 -0800587VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
588 webrtc::Call* call,
589 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200590 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800591 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800592 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000593}
594
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000595bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800596 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergff976312016-03-30 23:28:51 -0700597 LOG(LS_INFO) << "WebRtcVoiceEngine::ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800598 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800599
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000600 // kEcConference is AEC with high suppression.
601 webrtc::EcModes ec_mode = webrtc::kEcConference;
602 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
603 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
604 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700605 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000606 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700607 << *options.aecm_generate_comfort_noise
608 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000609 }
610
kjellanderfcfc8042016-01-14 11:01:09 -0800611#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000612 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100613 options.echo_cancellation = rtc::Optional<bool>(false);
614 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200615 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000616#elif defined(ANDROID)
617 ec_mode = webrtc::kEcAecm;
618#endif
619
kjellanderfcfc8042016-01-14 11:01:09 -0800620#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000621 // Set the AGC mode for iOS as well despite disabling it above, to avoid
622 // unsupported configuration errors from webrtc.
623 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100624 options.typing_detection = rtc::Optional<bool>(false);
625 options.experimental_agc = rtc::Optional<bool>(false);
626 options.extended_filter_aec = rtc::Optional<bool>(false);
627 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000628#endif
629
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100630 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
631 // where the feature is not supported.
632 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800633#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700634 if (options.delay_agnostic_aec) {
635 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100636 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100637 options.echo_cancellation = rtc::Optional<bool>(true);
638 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100639 ec_mode = webrtc::kEcConference;
640 }
641 }
642#endif
643
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
645
kwiberg102c6a62015-10-30 02:47:38 -0700646 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000647 // Check if platform supports built-in EC. Currently only supported on
648 // Android and in combination with Java based audio layer.
649 // TODO(henrika): investigate possibility to support built-in EC also
650 // in combination with Open SL ES audio.
solenberg5b5129a2016-04-08 05:35:48 -0700651 const bool built_in_aec = adm()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200652 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200653 // Built-in EC exists on this device and use_delay_agnostic_aec is not
654 // overriding it. Enable/Disable it according to the echo_cancellation
655 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200656 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700657 *options.echo_cancellation && !use_delay_agnostic_aec;
solenberg5b5129a2016-04-08 05:35:48 -0700658 if (adm()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
Bjorn Volcker73f72102015-06-03 14:50:15 +0200659 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100660 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000661 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100662 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000663 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
664 }
665 }
kwiberg102c6a62015-10-30 02:47:38 -0700666 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
667 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000668 return false;
669 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700670 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200671 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000672 }
673#if !defined(ANDROID)
674 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700675 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
676 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000677 return false;
678 }
679#endif
680 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700681 bool cn = options.aecm_generate_comfort_noise.value_or(false);
682 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
683 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000684 return false;
685 }
686 }
687 }
688
kwiberg102c6a62015-10-30 02:47:38 -0700689 if (options.auto_gain_control) {
solenberg5b5129a2016-04-08 05:35:48 -0700690 const bool built_in_agc = adm()->BuiltInAGCIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200691 if (built_in_agc) {
solenberg5b5129a2016-04-08 05:35:48 -0700692 if (adm()->EnableBuiltInAGC(*options.auto_gain_control) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700693 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200694 // Disable internal software AGC if built-in AGC is enabled,
695 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100696 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200697 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
698 }
699 }
kwiberg102c6a62015-10-30 02:47:38 -0700700 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
701 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000702 return false;
703 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700704 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
705 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000706 }
707 }
708
kwiberg102c6a62015-10-30 02:47:38 -0700709 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
710 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000711 // Override default_agc_config_. Generally, an unset option means "leave
712 // the VoE bits alone" in this function, so we want whatever is set to be
713 // stored as the new "default". If we didn't, then setting e.g.
714 // tx_agc_target_dbov would reset digital compression gain and limiter
715 // settings.
716 // Also, if we don't update default_agc_config_, then adjust_agc_delta
717 // would be an offset from the original values, and not whatever was set
718 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700719 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
720 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000721 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700722 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000723 default_agc_config_.digitalCompressionGaindB);
724 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700725 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000726 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
727 LOG_RTCERR3(SetAgcConfig,
728 default_agc_config_.targetLeveldBOv,
729 default_agc_config_.digitalCompressionGaindB,
730 default_agc_config_.limiterEnable);
731 return false;
732 }
733 }
734
kwiberg102c6a62015-10-30 02:47:38 -0700735 if (options.noise_suppression) {
solenberg5b5129a2016-04-08 05:35:48 -0700736 const bool built_in_ns = adm()->BuiltInNSIsAvailable();
henrikac14f5ff2015-09-23 14:08:33 +0200737 if (built_in_ns) {
solenberg5b5129a2016-04-08 05:35:48 -0700738 if (adm()->EnableBuiltInNS(*options.noise_suppression) == 0 &&
kwiberg102c6a62015-10-30 02:47:38 -0700739 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200740 // Disable internal software NS if built-in NS is enabled,
741 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100742 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200743 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
744 }
745 }
kwiberg102c6a62015-10-30 02:47:38 -0700746 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
747 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000748 return false;
749 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700750 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200751 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000752 }
753 }
754
kwiberg102c6a62015-10-30 02:47:38 -0700755 if (options.highpass_filter) {
756 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
757 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
758 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000759 return false;
760 }
761 }
762
kwiberg102c6a62015-10-30 02:47:38 -0700763 if (options.stereo_swapping) {
764 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
765 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
766 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
767 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000768 return false;
769 }
770 }
771
kwiberg102c6a62015-10-30 02:47:38 -0700772 if (options.audio_jitter_buffer_max_packets) {
773 LOG(LS_INFO) << "NetEq capacity is "
774 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200775 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700776 new webrtc::NetEqCapacityConfig(
777 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200778 }
779
kwiberg102c6a62015-10-30 02:47:38 -0700780 if (options.audio_jitter_buffer_fast_accelerate) {
781 LOG(LS_INFO) << "NetEq fast mode? "
782 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200783 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700784 new webrtc::NetEqFastAccelerate(
785 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200786 }
787
kwiberg102c6a62015-10-30 02:47:38 -0700788 if (options.typing_detection) {
789 LOG(LS_INFO) << "Typing detection is enabled? "
790 << *options.typing_detection;
791 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000792 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700793 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000794 }
795 }
796
kwiberg102c6a62015-10-30 02:47:38 -0700797 if (options.adjust_agc_delta) {
798 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
799 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000800 return false;
801 }
802 }
803
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000804 webrtc::Config config;
805
kwiberg102c6a62015-10-30 02:47:38 -0700806 if (options.delay_agnostic_aec)
807 delay_agnostic_aec_ = options.delay_agnostic_aec;
808 if (delay_agnostic_aec_) {
809 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700810 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700811 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100812 }
813
kwiberg102c6a62015-10-30 02:47:38 -0700814 if (options.extended_filter_aec) {
815 extended_filter_aec_ = options.extended_filter_aec;
816 }
817 if (extended_filter_aec_) {
818 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200819 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700820 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000821 }
822
kwiberg102c6a62015-10-30 02:47:38 -0700823 if (options.experimental_ns) {
824 experimental_ns_ = options.experimental_ns;
825 }
826 if (experimental_ns_) {
827 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000828 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700829 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000830 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000831
832 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
833 // returns NULL on audio_processing().
834 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
835 if (audioproc) {
836 audioproc->SetExtraOptions(config);
837 }
838
kwiberg102c6a62015-10-30 02:47:38 -0700839 if (options.recording_sample_rate) {
840 LOG(LS_INFO) << "Recording sample rate is "
841 << *options.recording_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700842 if (adm()->SetRecordingSampleRate(*options.recording_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700843 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000844 }
845 }
846
kwiberg102c6a62015-10-30 02:47:38 -0700847 if (options.playout_sample_rate) {
848 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
solenberg5b5129a2016-04-08 05:35:48 -0700849 if (adm()->SetPlayoutSampleRate(*options.playout_sample_rate)) {
kwiberg102c6a62015-10-30 02:47:38 -0700850 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000851 }
852 }
853
854 return true;
855}
856
solenberg246b8172015-12-08 09:50:23 -0800857void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800858 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800859#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800860 int in_id = kDefaultAudioDeviceId;
861 int out_id = kDefaultAudioDeviceId;
862 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
863 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000864
solenbergc1a1b352015-09-22 13:31:20 -0700865 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800866 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
867 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000868 ret = false;
869 }
solenberg246b8172015-12-08 09:50:23 -0800870 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
871 if (ap) {
872 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 }
874
solenberg246b8172015-12-08 09:50:23 -0800875 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
876 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877 ret = false;
878 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000880 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800881 LOG(LS_INFO) << "Set microphone to (id=" << in_id
882 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 }
kjellanderfcfc8042016-01-14 11:01:09 -0800884#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885}
886
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800888 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 unsigned int ulevel;
890 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
891 LOG_RTCERR1(GetSpeakerVolume, level);
892 return false;
893 }
894 *level = ulevel;
895 return true;
896}
897
898bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800899 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700900 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
902 LOG_RTCERR1(SetSpeakerVolume, level);
903 return false;
904 }
905 return true;
906}
907
908int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800909 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910 unsigned int ulevel;
911 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
912 static_cast<int>(ulevel) : -1;
913}
914
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800916 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return codecs_;
918}
919
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100920RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800921 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100922 RtpCapabilities capabilities;
923 capabilities.header_extensions.push_back(RtpHeaderExtension(
924 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
925 capabilities.header_extensions.push_back(
926 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
927 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800928 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
929 "Enabled") {
930 capabilities.header_extensions.push_back(RtpHeaderExtension(
931 kRtpTransportSequenceNumberHeaderExtension,
932 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
933 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100934 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935}
936
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800938 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 return voe_wrapper_->error();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
943 int length) {
solenberg566ef242015-11-06 15:34:49 -0800944 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000945 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000947 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000949 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000951 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000953 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954
solenberg72e29d22016-03-08 06:35:16 -0800955 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 if (length < 72) {
957 std::string msg(trace, length);
958 LOG(LS_ERROR) << "Malformed webrtc log message: ";
959 LOG_V(sev) << msg;
960 } else {
961 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +0200962 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 }
964}
965
solenberg63b34542015-09-29 06:06:31 -0700966void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800967 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
968 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 channels_.push_back(channel);
970}
971
solenberg63b34542015-09-29 06:06:31 -0700972void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800973 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -0700974 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -0800975 RTC_DCHECK(it != channels_.end());
976 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977}
978
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979// Adjusts the default AGC target level by the specified delta.
980// NB: If we start messing with other config fields, we'll want
981// to save the current webrtc::AgcConfig as well.
982bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -0800983 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 webrtc::AgcConfig config = default_agc_config_;
985 config.targetLeveldBOv -= delta;
986
987 LOG(LS_INFO) << "Adjusting AGC level from default -"
988 << default_agc_config_.targetLeveldBOv << "dB to -"
989 << config.targetLeveldBOv << "dB";
990
991 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
992 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
993 return false;
994 }
995 return true;
996}
997
ivocd66b44d2016-01-15 03:06:36 -0800998bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
999 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -08001000 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001001 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001002 if (!aec_dump_file_stream) {
1003 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001004 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001005 LOG(LS_WARNING) << "Could not close file.";
1006 return false;
1007 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001008 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001009 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1010 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001011 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001012 LOG_RTCERR0(StartDebugRecording);
1013 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001014 return false;
1015 }
1016 is_dumping_aec_ = true;
1017 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001018}
1019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001021 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 if (!is_dumping_aec_) {
1023 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001024 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1025 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001026 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027 } else {
1028 is_dumping_aec_ = true;
1029 }
1030 }
1031}
1032
1033void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001034 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 if (is_dumping_aec_) {
1036 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001037 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 webrtc::AudioProcessing::kNoError) {
1039 LOG_RTCERR0(StopDebugRecording);
1040 }
1041 is_dumping_aec_ = false;
1042 }
1043}
1044
ivoc112a3d82015-10-16 02:22:18 -07001045bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001046 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001047 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1048 if (event_log) {
1049 return event_log->StartLogging(file);
1050 }
1051 LOG_RTCERR0(StartRtcEventLog);
1052 return false;
ivoc112a3d82015-10-16 02:22:18 -07001053}
1054
1055void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001056 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001057 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1058 if (event_log) {
1059 event_log->StopLogging();
1060 return;
1061 }
1062 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001063}
1064
solenberg0a617e22015-10-20 15:49:38 -07001065int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001066 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001067 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001068}
1069
solenberg5b5129a2016-04-08 05:35:48 -07001070webrtc::AudioDeviceModule* WebRtcVoiceEngine::adm() {
1071 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1072 RTC_DCHECK(adm_);
1073 return adm_;
1074}
1075
solenbergc96df772015-10-21 13:01:53 -07001076class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001077 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001078 public:
skvlade0d46372016-04-07 22:59:22 -07001079 WebRtcAudioSendStream(int ch,
1080 webrtc::AudioTransport* voe_audio_transport,
1081 uint32_t ssrc,
1082 const std::string& c_name,
solenberg3a941542015-11-16 07:34:50 -08001083 const std::vector<webrtc::RtpExtension>& extensions,
1084 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001085 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001086 call_(call),
skvlade0d46372016-04-07 22:59:22 -07001087 config_(nullptr),
1088 rtp_parameters_(CreateRtpParametersWithOneEncoding()) {
solenberg85a04962015-10-27 03:35:21 -07001089 RTC_DCHECK_GE(ch, 0);
1090 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1091 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001092 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001093 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001094 config_.rtp.ssrc = ssrc;
1095 config_.rtp.c_name = c_name;
1096 config_.voe_channel_id = ch;
1097 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001098 }
solenberg3a941542015-11-16 07:34:50 -08001099
solenbergc96df772015-10-21 13:01:53 -07001100 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001101 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001102 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001103 call_->DestroyAudioSendStream(stream_);
1104 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001105
solenberg3a941542015-11-16 07:34:50 -08001106 void RecreateAudioSendStream(
1107 const std::vector<webrtc::RtpExtension>& extensions) {
1108 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1109 if (stream_) {
1110 call_->DestroyAudioSendStream(stream_);
1111 stream_ = nullptr;
1112 }
1113 config_.rtp.extensions = extensions;
1114 RTC_DCHECK(!stream_);
1115 stream_ = call_->CreateAudioSendStream(config_);
1116 RTC_CHECK(stream_);
solenberg6d6e7c52016-04-13 09:07:30 -07001117 UpdateSendState();
solenberg3a941542015-11-16 07:34:50 -08001118 }
1119
solenberg8842c3e2016-03-11 03:06:41 -08001120 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001121 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1122 RTC_DCHECK(stream_);
1123 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1124 }
1125
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001126 void SetSend(bool send) {
1127 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1128 send_ = send;
1129 UpdateSendState();
1130 }
1131
solenberg3a941542015-11-16 07:34:50 -08001132 webrtc::AudioSendStream::Stats GetStats() const {
1133 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1134 RTC_DCHECK(stream_);
1135 return stream_->GetStats();
1136 }
1137
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001138 // Starts the sending by setting ourselves as a sink to the AudioSource to
1139 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001140 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001141 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001142 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001143 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001144 RTC_DCHECK(source);
1145 if (source_) {
1146 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001147 return;
1148 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001149 source->SetSink(this);
1150 source_ = source;
1151 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001152 }
1153
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001154 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001155 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001156 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001157 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001158 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001159 if (source_) {
1160 source_->SetSink(nullptr);
1161 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001162 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001163 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001164 }
1165
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001166 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001167 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001168 void OnData(const void* audio_data,
1169 int bits_per_sample,
1170 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001171 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001172 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001173 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001174 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001175 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001176 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001177 audio_data,
1178 bits_per_sample,
1179 sample_rate,
1180 number_of_channels,
1181 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001182 }
1183
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001184 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001185 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001186 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001187 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001188 // Set |source_| to nullptr to make sure no more callback will get into
1189 // the source.
1190 source_ = nullptr;
1191 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001192 }
1193
1194 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001195 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001196 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001197 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001198 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001199
skvlade0d46372016-04-07 22:59:22 -07001200 const webrtc::RtpParameters& rtp_parameters() const {
1201 return rtp_parameters_;
1202 }
1203
1204 void set_rtp_parameters(const webrtc::RtpParameters& parameters) {
1205 RTC_CHECK_EQ(1UL, parameters.encodings.size());
1206 rtp_parameters_ = parameters;
1207 }
1208
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001209 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001210 void UpdateSendState() {
1211 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1212 RTC_DCHECK(stream_);
1213 if (send_ && source_ != nullptr) {
1214 stream_->Start();
1215 } else { // !send || source_ = nullptr
1216 stream_->Stop();
1217 }
1218 }
1219
solenberg566ef242015-11-06 15:34:49 -08001220 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001221 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001222 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1223 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001224 webrtc::AudioSendStream::Config config_;
1225 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1226 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001227 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001228
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001229 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001230 // PeerConnection will make sure invalidating the pointer before the object
1231 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001232 AudioSource* source_ = nullptr;
1233 bool send_ = false;
skvlade0d46372016-04-07 22:59:22 -07001234 webrtc::RtpParameters rtp_parameters_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001235
solenbergc96df772015-10-21 13:01:53 -07001236 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1237};
1238
1239class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1240 public:
stefanba4c0e42016-02-04 04:12:24 -08001241 WebRtcAudioReceiveStream(int ch,
1242 uint32_t remote_ssrc,
1243 uint32_t local_ssrc,
1244 bool use_transport_cc,
1245 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001246 const std::vector<webrtc::RtpExtension>& extensions,
1247 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001248 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001249 RTC_DCHECK_GE(ch, 0);
1250 RTC_DCHECK(call);
1251 config_.rtp.remote_ssrc = remote_ssrc;
1252 config_.rtp.local_ssrc = local_ssrc;
1253 config_.voe_channel_id = ch;
1254 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001255 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001256 }
solenbergc96df772015-10-21 13:01:53 -07001257
solenberg7add0582015-11-20 09:59:34 -08001258 ~WebRtcAudioReceiveStream() {
1259 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1260 call_->DestroyAudioReceiveStream(stream_);
1261 }
1262
1263 void RecreateAudioReceiveStream(
1264 const std::vector<webrtc::RtpExtension>& extensions) {
1265 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001266 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001267 }
stefanba4c0e42016-02-04 04:12:24 -08001268 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001269 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001270 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001271 }
1272
1273 webrtc::AudioReceiveStream::Stats GetStats() const {
1274 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1275 RTC_DCHECK(stream_);
1276 return stream_->GetStats();
1277 }
1278
1279 int channel() const {
1280 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1281 return config_.voe_channel_id;
1282 }
solenbergc96df772015-10-21 13:01:53 -07001283
kwiberg686a8ef2016-02-26 03:00:35 -08001284 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001285 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001286 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001287 }
1288
solenbergc96df772015-10-21 13:01:53 -07001289 private:
stefanba4c0e42016-02-04 04:12:24 -08001290 void RecreateAudioReceiveStream(
1291 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001292 const std::vector<webrtc::RtpExtension>& extensions) {
1293 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1294 if (stream_) {
1295 call_->DestroyAudioReceiveStream(stream_);
1296 stream_ = nullptr;
1297 }
1298 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001299 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001300 RTC_DCHECK(!stream_);
1301 stream_ = call_->CreateAudioReceiveStream(config_);
1302 RTC_CHECK(stream_);
1303 }
1304
1305 rtc::ThreadChecker worker_thread_checker_;
1306 webrtc::Call* call_ = nullptr;
1307 webrtc::AudioReceiveStream::Config config_;
1308 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1309 // configuration changes.
1310 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001311
1312 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001313};
1314
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001315WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001316 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001317 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001318 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001319 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001320 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001321 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001322 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001323 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324}
1325
1326WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001327 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001328 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001329 // TODO(solenberg): Should be able to delete the streams directly, without
1330 // going through RemoveNnStream(), once stream objects handle
1331 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001332 while (!send_streams_.empty()) {
1333 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001334 }
solenberg7add0582015-11-20 09:59:34 -08001335 while (!recv_streams_.empty()) {
1336 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 }
solenberg0a617e22015-10-20 15:49:38 -07001338 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339}
1340
nisse51542be2016-02-12 02:27:06 -08001341rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1342 return kAudioDscpValue;
1343}
1344
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001345bool WebRtcVoiceMediaChannel::SetSendParameters(
1346 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001347 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001348 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001349 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1350 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001351 // TODO(pthatcher): Refactor this to be more clean now that we have
1352 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001353
1354 if (!SetSendCodecs(params.codecs)) {
1355 return false;
1356 }
1357
solenberg7e4e01a2015-12-02 08:05:01 -08001358 if (!ValidateRtpExtensions(params.extensions)) {
1359 return false;
1360 }
1361 std::vector<webrtc::RtpExtension> filtered_extensions =
1362 FilterRtpExtensions(params.extensions,
1363 webrtc::RtpExtension::IsSupportedForAudio, true);
1364 if (send_rtp_extensions_ != filtered_extensions) {
1365 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001366 for (auto& it : send_streams_) {
1367 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1368 }
1369 }
1370
skvlade0d46372016-04-07 22:59:22 -07001371 if (!SetSendBitrate(params.max_bandwidth_bps)) {
solenberg3a941542015-11-16 07:34:50 -08001372 return false;
1373 }
1374 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001375}
1376
1377bool WebRtcVoiceMediaChannel::SetRecvParameters(
1378 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001379 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001380 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001381 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1382 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001383 // TODO(pthatcher): Refactor this to be more clean now that we have
1384 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001385
1386 if (!SetRecvCodecs(params.codecs)) {
1387 return false;
1388 }
1389
solenberg7e4e01a2015-12-02 08:05:01 -08001390 if (!ValidateRtpExtensions(params.extensions)) {
1391 return false;
1392 }
1393 std::vector<webrtc::RtpExtension> filtered_extensions =
1394 FilterRtpExtensions(params.extensions,
1395 webrtc::RtpExtension::IsSupportedForAudio, false);
1396 if (recv_rtp_extensions_ != filtered_extensions) {
1397 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001398 for (auto& it : recv_streams_) {
1399 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1400 }
1401 }
solenberg7add0582015-11-20 09:59:34 -08001402 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001403}
1404
skvlade0d46372016-04-07 22:59:22 -07001405webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpParameters(
1406 uint32_t ssrc) const {
1407 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1408 auto it = send_streams_.find(ssrc);
1409 if (it == send_streams_.end()) {
1410 LOG(LS_WARNING) << "Attempting to get RTP parameters for stream with ssrc "
1411 << ssrc << " which doesn't exist.";
1412 return webrtc::RtpParameters();
1413 }
1414
1415 return it->second->rtp_parameters();
1416}
1417
1418bool WebRtcVoiceMediaChannel::SetRtpParameters(
1419 uint32_t ssrc,
1420 const webrtc::RtpParameters& parameters) {
1421 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1422 if (!ValidateRtpParameters(parameters)) {
1423 return false;
1424 }
1425 auto it = send_streams_.find(ssrc);
1426 if (it == send_streams_.end()) {
1427 LOG(LS_WARNING) << "Attempting to set RTP parameters for stream with ssrc "
1428 << ssrc << " which doesn't exist.";
1429 return false;
1430 }
1431
1432 if (!SetChannelParameters(it->second->channel(), parameters)) {
1433 LOG(LS_WARNING) << "Failed to set RtpParameters.";
1434 return false;
1435 }
1436 it->second->set_rtp_parameters(parameters);
1437 return true;
1438}
1439
1440bool WebRtcVoiceMediaChannel::ValidateRtpParameters(
1441 const webrtc::RtpParameters& rtp_parameters) {
1442 if (rtp_parameters.encodings.size() != 1) {
1443 LOG(LS_ERROR)
1444 << "Attempted to set RtpParameters without exactly one encoding";
1445 return false;
1446 }
1447 return true;
1448}
1449
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001451 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 LOG(LS_INFO) << "Setting voice channel options: "
1453 << options.ToString();
1454
1455 // We retain all of the existing options, and apply the given ones
1456 // on top. This means there is no way to "clear" options such that
1457 // they go back to the engine default.
1458 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001459 if (!engine()->ApplyOptions(options_)) {
1460 LOG(LS_WARNING) <<
1461 "Failed to apply engine options during channel SetOptions.";
1462 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464 LOG(LS_INFO) << "Set voice channel options. Current options: "
1465 << options_.ToString();
1466 return true;
1467}
1468
1469bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1470 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001471 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001472
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001474 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001475
1476 if (!VerifyUniquePayloadTypes(codecs)) {
1477 LOG(LS_ERROR) << "Codec payload types overlap.";
1478 return false;
1479 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480
1481 std::vector<AudioCodec> new_codecs;
1482 // Find all new codecs. We allow adding new codecs but don't allow changing
1483 // the payload type of codecs that is already configured since we might
1484 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001485 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001487 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1488 if (old_codec.id != codec.id) {
1489 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490 return false;
1491 }
1492 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001493 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494 }
1495 }
1496 if (new_codecs.empty()) {
1497 // There are no new codecs to configure. Already configured codecs are
1498 // never removed.
1499 return true;
1500 }
1501
1502 if (playout_) {
1503 // Receive codecs can not be changed while playing. So we temporarily
1504 // pause playout.
1505 PausePlayout();
1506 }
1507
solenberg26c8c912015-11-27 04:00:25 -08001508 bool result = true;
1509 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001510 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001511 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1512 LOG(LS_INFO) << ToString(codec);
1513 voe_codec.pltype = codec.id;
1514 for (const auto& ch : recv_streams_) {
1515 if (engine()->voe()->codec()->SetRecPayloadType(
1516 ch.second->channel(), voe_codec) == -1) {
1517 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1518 ToString(voe_codec));
1519 result = false;
1520 }
1521 }
1522 } else {
1523 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1524 result = false;
1525 break;
1526 }
1527 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001528 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529 recv_codecs_ = codecs;
1530 }
1531
1532 if (desired_playout_ && !playout_) {
1533 ResumePlayout();
1534 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001535 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536}
1537
solenberg72e29d22016-03-08 06:35:16 -08001538// Utility function called from SetSendParameters() to extract current send
1539// codec settings from the given list of codecs (originally from SDP). Both send
1540// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001541bool WebRtcVoiceMediaChannel::SetSendCodecs(
1542 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001543 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001544 // TODO(solenberg): Validate input - that payload types don't overlap, are
1545 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001546 // redundant codecs etc - the same way it is done for
1547 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001548
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001549 // Find the DTMF telephone event "codec" payload type.
1550 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001551 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001552 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001553 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1554 return false;
1555 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001556 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1557 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001558 }
1559 }
1560
solenberg72e29d22016-03-08 06:35:16 -08001561 // Scan through the list to figure out the codec to use for sending, along
1562 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1563 // parameters.
1564 {
1565 SendCodecSpec send_codec_spec;
1566 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1567
1568 // Find send codec (the first non-telephone-event/CN codec).
1569 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1570 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1571 if (!codec) {
1572 LOG(LS_WARNING) << "Received empty list of codecs.";
1573 return false;
1574 }
1575
1576 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1577
1578 // This condition is apparently here because Opus does not support RED and
1579 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1580 // such limitations.
1581 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1582 if (send_codec_spec.red_payload_type == -1) {
1583 send_codec_spec.nack_enabled = HasNack(*codec);
1584 // For Opus as the send codec, we are to determine inband FEC, maximum
1585 // playback rate, and opus internal dtx.
1586 if (IsCodec(*codec, kOpusCodecName)) {
1587 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1588 &send_codec_spec.enable_codec_fec,
1589 &send_codec_spec.opus_max_playback_rate,
1590 &send_codec_spec.enable_opus_dtx);
1591 }
1592
1593 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1594 int ptime_ms = 0;
1595 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1596 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1597 &send_codec_spec.codec_inst, ptime_ms)) {
1598 LOG(LS_WARNING) << "Failed to set packet size for codec "
1599 << send_codec_spec.codec_inst.plname;
1600 return false;
1601 }
1602 }
1603 }
1604
1605 // Loop through the codecs list again to find the CN codec.
1606 // TODO(solenberg): Break out into a separate function?
1607 for (const AudioCodec& codec : codecs) {
1608 // Ignore codecs we don't know about. The negotiation step should prevent
1609 // this, but double-check to be sure.
1610 webrtc::CodecInst voe_codec = {0};
1611 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1612 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1613 continue;
1614 }
1615
1616 if (IsCodec(codec, kCnCodecName)) {
1617 // Turn voice activity detection/comfort noise on if supported.
1618 // Set the wideband CN payload type appropriately.
1619 // (narrowband always uses the static payload type 13).
1620 int cng_plfreq = -1;
1621 switch (codec.clockrate) {
1622 case 8000:
1623 case 16000:
1624 case 32000:
1625 cng_plfreq = codec.clockrate;
1626 break;
1627 default:
1628 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1629 << " not supported.";
1630 continue;
1631 }
1632 send_codec_spec.cng_payload_type = codec.id;
1633 send_codec_spec.cng_plfreq = cng_plfreq;
1634 break;
1635 }
1636 }
1637
1638 // Latch in the new state.
1639 send_codec_spec_ = std::move(send_codec_spec);
1640 }
1641
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001642 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001643 for (const auto& ch : send_streams_) {
skvlade0d46372016-04-07 22:59:22 -07001644 if (!SetSendCodecs(ch.second->channel(), ch.second->rtp_parameters())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001645 return false;
1646 }
1647 }
1648
solenberg72e29d22016-03-08 06:35:16 -08001649 // Set nack status on receive channels.
1650 if (!send_streams_.empty()) {
1651 for (const auto& kv : recv_streams_) {
1652 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1653 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001654 }
solenberg0a617e22015-10-20 15:49:38 -07001655
stefanba4c0e42016-02-04 04:12:24 -08001656 // Check if the transport cc feedback has changed on the preferred send codec,
1657 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001658 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1659 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1660 "codec has changed.";
1661 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1662 for (auto& kv : recv_streams_) {
1663 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1664 }
1665 }
1666
1667 return true;
1668}
1669
1670// Apply current codec settings to a single voe::Channel used for sending.
skvlade0d46372016-04-07 22:59:22 -07001671bool WebRtcVoiceMediaChannel::SetSendCodecs(
1672 int channel,
1673 const webrtc::RtpParameters& rtp_parameters) {
solenberg72e29d22016-03-08 06:35:16 -08001674 // Disable VAD, FEC, and RED unless we know the other side wants them.
1675 engine()->voe()->codec()->SetVADStatus(channel, false);
1676 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1677 engine()->voe()->rtp()->SetREDStatus(channel, false);
1678 engine()->voe()->codec()->SetFECStatus(channel, false);
1679
1680 if (send_codec_spec_.red_payload_type != -1) {
1681 // Enable redundant encoding of the specified codec. Treat any
1682 // failure as a fatal internal error.
1683 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1684 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1685 send_codec_spec_.red_payload_type) == -1) {
1686 LOG_RTCERR3(SetREDStatus, channel, true,
1687 send_codec_spec_.red_payload_type);
1688 return false;
1689 }
1690 }
1691
1692 SetNack(channel, send_codec_spec_.nack_enabled);
1693
1694 // Set the codec immediately, since SetVADStatus() depends on whether
1695 // the current codec is mono or stereo.
1696 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1697 return false;
1698 }
1699
1700 // FEC should be enabled after SetSendCodec.
1701 if (send_codec_spec_.enable_codec_fec) {
1702 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1703 << channel;
1704 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1705 // Enable codec internal FEC. Treat any failure as fatal internal error.
1706 LOG_RTCERR2(SetFECStatus, channel, true);
1707 return false;
1708 }
1709 }
1710
1711 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1712 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1713 // send codec has to be Opus.
1714
1715 // Set Opus internal DTX.
1716 LOG(LS_INFO) << "Attempt to "
1717 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1718 << " Opus DTX on channel "
1719 << channel;
1720 if (engine()->voe()->codec()->SetOpusDtx(channel,
1721 send_codec_spec_.enable_opus_dtx)) {
1722 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1723 return false;
1724 }
1725
1726 // If opus_max_playback_rate <= 0, the default maximum playback rate
1727 // (48 kHz) will be used.
1728 if (send_codec_spec_.opus_max_playback_rate > 0) {
1729 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1730 << send_codec_spec_.opus_max_playback_rate
1731 << " Hz on channel "
1732 << channel;
1733 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1734 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1735 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1736 send_codec_spec_.opus_max_playback_rate);
1737 return false;
stefanba4c0e42016-02-04 04:12:24 -08001738 }
1739 }
1740 }
skvlade0d46372016-04-07 22:59:22 -07001741 // TODO(solenberg): SetSendBitrate() yields another call to SetSendCodec().
1742 // Check if it is possible to fuse with the previous call in this function.
1743 SetChannelParameters(channel, rtp_parameters);
solenberg72e29d22016-03-08 06:35:16 -08001744
1745 // Set the CN payloadtype and the VAD status.
1746 if (send_codec_spec_.cng_payload_type != -1) {
1747 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1748 if (send_codec_spec_.cng_plfreq != 8000) {
1749 webrtc::PayloadFrequencies cn_freq;
1750 switch (send_codec_spec_.cng_plfreq) {
1751 case 16000:
1752 cn_freq = webrtc::kFreq16000Hz;
1753 break;
1754 case 32000:
1755 cn_freq = webrtc::kFreq32000Hz;
1756 break;
1757 default:
1758 RTC_NOTREACHED();
1759 return false;
1760 }
1761 if (engine()->voe()->codec()->SetSendCNPayloadType(
1762 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1763 LOG_RTCERR3(SetSendCNPayloadType, channel,
1764 send_codec_spec_.cng_payload_type, cn_freq);
1765 // TODO(ajm): This failure condition will be removed from VoE.
1766 // Restore the return here when we update to a new enough webrtc.
1767 //
1768 // Not returning false because the SetSendCNPayloadType will fail if
1769 // the channel is already sending.
1770 // This can happen if the remote description is applied twice, for
1771 // example in the case of ROAP on top of JSEP, where both side will
1772 // send the offer.
1773 }
1774 }
1775
1776 // Only turn on VAD if we have a CN payload type that matches the
1777 // clockrate for the codec we are going to use.
1778 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1779 send_codec_spec_.codec_inst.channels == 1) {
1780 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1781 // interaction between VAD and Opus FEC.
1782 LOG(LS_INFO) << "Enabling VAD";
1783 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1784 LOG_RTCERR2(SetVADStatus, channel, true);
1785 return false;
1786 }
1787 }
1788 }
solenberg0a617e22015-10-20 15:49:38 -07001789 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001790}
1791
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001792void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001794 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1796 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001797 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1799 }
1800}
1801
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001803 int channel, const webrtc::CodecInst& send_codec) {
1804 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1805 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1806
solenberg72e29d22016-03-08 06:35:16 -08001807 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001808 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1809 (send_codec == current_codec)) {
1810 // Codec is already configured, we can return without setting it again.
1811 return true;
1812 }
1813
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001814 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1815 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816 return false;
1817 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818 return true;
1819}
1820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1822 desired_playout_ = playout;
1823 return ChangePlayout(desired_playout_);
1824}
1825
1826bool WebRtcVoiceMediaChannel::PausePlayout() {
1827 return ChangePlayout(false);
1828}
1829
1830bool WebRtcVoiceMediaChannel::ResumePlayout() {
1831 return ChangePlayout(desired_playout_);
1832}
1833
1834bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001835 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001836 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837 if (playout_ == playout) {
1838 return true;
1839 }
1840
solenberg7add0582015-11-20 09:59:34 -08001841 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001842 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001843 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001844 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001845 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 }
1847 }
solenberg1ac56142015-10-13 03:58:19 -07001848 playout_ = playout;
1849 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850}
1851
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001852void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001853 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001855 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 }
1857
solenberg246b8172015-12-08 09:50:23 -08001858 // Apply channel specific options when channel is enabled for sending.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001859 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001860 engine()->ApplyOptions(options_);
1861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001863 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001864 for (auto& kv : send_streams_) {
1865 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001867
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001868 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001869}
1870
Peter Boström0c4e06b2015-10-07 12:23:21 +02001871bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1872 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001873 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001874 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001875 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001876 // TODO(solenberg): The state change should be fully rolled back if any one of
1877 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001878 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001879 return false;
1880 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001881 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001882 return false;
1883 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001884 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001885 return SetOptions(*options);
1886 }
1887 return true;
1888}
1889
solenberg0a617e22015-10-20 15:49:38 -07001890int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1891 int id = engine()->CreateVoEChannel();
1892 if (id == -1) {
1893 LOG_RTCERR0(CreateVoEChannel);
1894 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001895 }
solenberg0a617e22015-10-20 15:49:38 -07001896 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1897 LOG_RTCERR2(RegisterExternalTransport, id, this);
1898 engine()->voe()->base()->DeleteChannel(id);
1899 return -1;
1900 }
1901 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001902}
1903
solenberg7add0582015-11-20 09:59:34 -08001904bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001905 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1906 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1907 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001908 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1909 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 return false;
1911 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001912 return true;
1913}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001914
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001915bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001916 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001917 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001918 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1919
1920 uint32_t ssrc = sp.first_ssrc();
1921 RTC_DCHECK(0 != ssrc);
1922
1923 if (GetSendChannelId(ssrc) != -1) {
1924 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001925 return false;
1926 }
1927
solenberg0a617e22015-10-20 15:49:38 -07001928 // Create a new channel for sending audio data.
1929 int channel = CreateVoEChannel();
1930 if (channel == -1) {
1931 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001932 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001933
solenbergc96df772015-10-21 13:01:53 -07001934 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001935 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001936 webrtc::AudioTransport* audio_transport =
1937 engine()->voe()->base()->audio_transport();
skvlade0d46372016-04-07 22:59:22 -07001938 WebRtcAudioSendStream* stream = new WebRtcAudioSendStream(
1939 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_);
1940 send_streams_.insert(std::make_pair(ssrc, stream));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001941
solenberg0a617e22015-10-20 15:49:38 -07001942 // Set the current codecs to be used for the new channel. We need to do this
1943 // after adding the channel to send_channels_, because of how max bitrate is
1944 // currently being configured by SetSendCodec().
skvlade0d46372016-04-07 22:59:22 -07001945 if (HasSendCodec() && !SetSendCodecs(channel, stream->rtp_parameters())) {
solenberg0a617e22015-10-20 15:49:38 -07001946 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001947 return false;
1948 }
1949
1950 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001951 // the first send channel make sure that all the receive channels are updated
1952 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001953 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001954 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001955 for (const auto& stream : recv_streams_) {
1956 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001957 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001958 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001959 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001960 }
solenberg0a617e22015-10-20 15:49:38 -07001961 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1962 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1963 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001964 }
1965 }
1966
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001967 send_streams_[ssrc]->SetSend(send_);
1968 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001969}
1970
Peter Boström0c4e06b2015-10-07 12:23:21 +02001971bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001972 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001973 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001974 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1975
solenbergc96df772015-10-21 13:01:53 -07001976 auto it = send_streams_.find(ssrc);
1977 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001978 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1979 << " which doesn't exist.";
1980 return false;
1981 }
1982
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001983 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001984
solenberg7add0582015-11-20 09:59:34 -08001985 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001986 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001987 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1988 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001989 delete it->second;
1990 send_streams_.erase(it);
1991 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001992 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001993 }
solenbergc96df772015-10-21 13:01:53 -07001994 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001995 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07001996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 return true;
1998}
1999
2000bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002001 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002002 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002003 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2004
solenberg0b675462015-10-09 01:37:09 -07002005 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002006 return false;
2007 }
2008
solenberg7add0582015-11-20 09:59:34 -08002009 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002010 if (ssrc == 0) {
2011 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2012 return false;
2013 }
2014
solenberg1ac56142015-10-13 03:58:19 -07002015 // Remove the default receive stream if one had been created with this ssrc;
2016 // we'll recreate it then.
2017 if (IsDefaultRecvStream(ssrc)) {
2018 RemoveRecvStream(ssrc);
2019 }
solenberg0b675462015-10-09 01:37:09 -07002020
solenberg7add0582015-11-20 09:59:34 -08002021 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002022 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 return false;
2024 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002025
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002027 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 return false;
2030 }
Minyue2013aec2015-05-13 14:14:42 +02002031
solenberg1ac56142015-10-13 03:58:19 -07002032 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002033 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2034 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2035 voe_codec.pltype = -1;
2036 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2037 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2038 DeleteVoEChannel(channel);
2039 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040 }
2041 }
2042
solenberg1ac56142015-10-13 03:58:19 -07002043 // Only enable those configured for this channel.
2044 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002045 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002046 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002047 voe_codec.pltype = codec.id;
2048 if (engine()->voe()->codec()->SetRecPayloadType(
2049 channel, voe_codec) == -1) {
2050 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002051 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002052 return false;
2053 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002054 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055 }
solenberg8fb30c32015-10-13 03:06:58 -07002056
solenberg7add0582015-11-20 09:59:34 -08002057 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2058 if (send_channel != -1) {
2059 // Associate receive channel with first send channel (so the receive channel
2060 // can obtain RTT from the send channel)
2061 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2062 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2063 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002064 }
2065
stefanba4c0e42016-02-04 04:12:24 -08002066 recv_streams_.insert(std::make_pair(
2067 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002068 recv_transport_cc_enabled_,
2069 sp.sync_label, recv_rtp_extensions_,
2070 call_)));
solenberg7add0582015-11-20 09:59:34 -08002071
solenberg72e29d22016-03-08 06:35:16 -08002072 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002073 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002074
solenberg1ac56142015-10-13 03:58:19 -07002075 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076}
2077
Peter Boström0c4e06b2015-10-07 12:23:21 +02002078bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002079 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002080 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002081 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2082
solenberg7add0582015-11-20 09:59:34 -08002083 const auto it = recv_streams_.find(ssrc);
2084 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002085 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2086 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002087 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002088 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089
solenberg1ac56142015-10-13 03:58:19 -07002090 // Deregister default channel, if that's the one being destroyed.
2091 if (IsDefaultRecvStream(ssrc)) {
2092 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002094
solenberg7add0582015-11-20 09:59:34 -08002095 const int channel = it->second->channel();
2096
2097 // Clean up and delete the receive stream+channel.
2098 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002099 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002100 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002101 delete it->second;
2102 recv_streams_.erase(it);
2103 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002104}
2105
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002106bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2107 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002108 auto it = send_streams_.find(ssrc);
2109 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002110 if (source) {
2111 // Return an error if trying to set a valid source with an invalid ssrc.
2112 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002113 return false;
2114 }
2115
2116 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002117 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002118 }
2119
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002120 if (source) {
2121 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002122 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002123 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002124 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 return true;
2127}
2128
2129bool WebRtcVoiceMediaChannel::GetActiveStreams(
2130 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002131 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002133 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002134 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002136 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 }
2138 }
2139 return true;
2140}
2141
2142int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002143 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002144 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002145 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002146 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147 }
2148 return highest;
2149}
2150
2151int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2152 int ret;
2153 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2154 // In case of error, log the info and continue
2155 LOG_RTCERR0(TimeSinceLastTyping);
2156 ret = -1;
2157 } else {
2158 ret *= 1000; // We return ms, webrtc returns seconds.
2159 }
2160 return ret;
2161}
2162
2163void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2164 int cost_per_typing, int reporting_threshold, int penalty_decay,
2165 int type_event_delay) {
2166 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2167 time_window, cost_per_typing,
2168 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2169 // In case of error, log the info and continue
2170 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2171 cost_per_typing, reporting_threshold, penalty_decay,
2172 type_event_delay);
2173 }
2174}
2175
solenberg4bac9c52015-10-09 02:32:53 -07002176bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002177 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002178 if (ssrc == 0) {
2179 default_recv_volume_ = volume;
2180 if (default_recv_ssrc_ == -1) {
2181 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182 }
solenberg1ac56142015-10-13 03:58:19 -07002183 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2184 }
2185 int ch_id = GetReceiveChannelId(ssrc);
2186 if (ch_id < 0) {
2187 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2188 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 }
2190
solenberg1ac56142015-10-13 03:58:19 -07002191 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2192 volume)) {
2193 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2194 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002195 }
solenberg1ac56142015-10-13 03:58:19 -07002196 LOG(LS_INFO) << "SetOutputVolume to " << volume
2197 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 return true;
2199}
2200
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002202 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203}
2204
solenberg1d63dd02015-12-02 12:35:09 -08002205bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2206 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002207 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002208 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2209 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 return false;
2211 }
2212
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002213 // Figure out which WebRtcAudioSendStream to send the event on.
2214 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2215 if (it == send_streams_.end()) {
2216 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002217 return false;
2218 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002219 if (event < kMinTelephoneEventCode ||
2220 event > kMaxTelephoneEventCode) {
2221 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002222 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002224 if (duration < kMinTelephoneEventDuration ||
2225 duration > kMaxTelephoneEventDuration) {
2226 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2227 return false;
2228 }
2229 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230}
2231
wu@webrtc.orga9890802013-12-13 00:21:03 +00002232void WebRtcVoiceMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002233 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002234 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002235
solenberg1ac56142015-10-13 03:58:19 -07002236 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002237 if (!GetRtpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg1ac56142015-10-13 03:58:19 -07002238 return;
2239 }
2240
solenberg7e63ef02015-11-20 00:19:43 -08002241 // If we don't have a default channel, and the SSRC is unknown, create a
2242 // default channel.
2243 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002244 StreamParams sp;
2245 sp.ssrcs.push_back(ssrc);
2246 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2247 if (!AddRecvStream(sp)) {
2248 LOG(LS_WARNING) << "Could not create default receive stream.";
2249 return;
2250 }
2251 default_recv_ssrc_ = ssrc;
2252 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002253 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002254 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002255 new ProxySink(default_sink_.get()));
2256 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2257 }
solenberg1ac56142015-10-13 03:58:19 -07002258 }
2259
2260 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002261 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2262 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002263 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2264 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002265 packet->cdata(), packet->size(), webrtc_packet_time);
solenberg1ac56142015-10-13 03:58:19 -07002266 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002267 // If the SSRC is unknown here, route it to the default channel, if we have
2268 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2269 if (default_recv_ssrc_ == -1) {
2270 return;
2271 } else {
2272 ssrc = default_recv_ssrc_;
2273 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002274 }
2275
solenberg1ac56142015-10-13 03:58:19 -07002276 // Find the channel to send this packet to. It must exist since webrtc::Call
2277 // was able to demux the packet.
2278 int channel = GetReceiveChannelId(ssrc);
2279 RTC_DCHECK(channel != -1);
2280
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002282 engine()->voe()->network()->ReceivedRTPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002283 channel, packet->cdata(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284}
2285
wu@webrtc.orga9890802013-12-13 00:21:03 +00002286void WebRtcVoiceMediaChannel::OnRtcpReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002287 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002288 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002289
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002290 // Forward packet to Call as well.
2291 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2292 packet_time.not_before);
2293 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002294 packet->cdata(), packet->size(), webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002295
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002296 // Sending channels need all RTCP packets with feedback information.
2297 // Even sender reports can contain attached report blocks.
2298 // Receiving channels need sender reports in order to create
2299 // correct receiver reports.
2300 int type = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002301 if (!GetRtcpType(packet->cdata(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002302 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2303 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304 }
2305
solenberg0b675462015-10-09 01:37:09 -07002306 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002307 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002308 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002309 if (!GetRtcpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg0b675462015-10-09 01:37:09 -07002310 return;
2311 }
2312 int recv_channel_id = GetReceiveChannelId(ssrc);
2313 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002314 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002315 recv_channel_id, packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002316 }
2317 }
2318
2319 // SR may continue RR and any RR entry may correspond to any one of the send
2320 // channels. So all RTCP packets must be forwarded all send channels. VoE
2321 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002322 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002323 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002324 ch.second->channel(), packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002325 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326}
2327
Honghai Zhangcc411c02016-03-29 17:27:21 -07002328void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2329 const std::string& transport_name,
2330 const NetworkRoute& network_route) {
2331 // TODO(honghaiz): uncomment this once the function in call is implemented.
2332 // call_->OnNetworkRouteChanged(transport_name, network_route);
2333}
2334
Peter Boström0c4e06b2015-10-07 12:23:21 +02002335bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002336 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002337 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002338 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2340 return false;
2341 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002342 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2343 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 return false;
2345 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002346 // We set the AGC to mute state only when all the channels are muted.
2347 // This implementation is not ideal, instead we should signal the AGC when
2348 // the mic channel is muted/unmuted. We can't do it today because there
2349 // is no good way to know which stream is mapping to the mic channel.
2350 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002351 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002352 if (!all_muted) {
2353 break;
2354 }
2355 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002356 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002357 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002358 return false;
2359 }
2360 }
2361
2362 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002363 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002364 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002365 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002366 return true;
2367}
2368
skvlade0d46372016-04-07 22:59:22 -07002369bool WebRtcVoiceMediaChannel::SetSendBitrate(int bps) {
2370 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrate.";
2371 send_bitrate_bps_ = bps;
2372
2373 for (const auto& kv : send_streams_) {
2374 if (!SetChannelParameters(kv.second->channel(),
2375 kv.second->rtp_parameters())) {
2376 return false;
2377 }
2378 }
2379 return true;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002380}
2381
skvlade0d46372016-04-07 22:59:22 -07002382bool WebRtcVoiceMediaChannel::SetChannelParameters(
2383 int channel,
2384 const webrtc::RtpParameters& parameters) {
2385 RTC_CHECK_EQ(1UL, parameters.encodings.size());
2386 return SetSendBitrate(
2387 channel,
2388 MinPositive(send_bitrate_bps_, parameters.encodings[0].max_bitrate_bps));
2389}
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002390
skvlade0d46372016-04-07 22:59:22 -07002391bool WebRtcVoiceMediaChannel::SetSendBitrate(int channel, int bps) {
2392 // Bitrate is auto by default.
2393 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2394 // SetMaxSendBandwith(0), the second call removes the previous limit.
2395 if (bps <= 0)
2396 return true;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002397
solenberg72e29d22016-03-08 06:35:16 -08002398 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002399 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002400 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002401 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 }
2403
solenberg72e29d22016-03-08 06:35:16 -08002404 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002405 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406
2407 if (is_multi_rate) {
2408 // If codec is multi-rate then just set the bitrate.
2409 codec.rate = bps;
skvlade0d46372016-04-07 22:59:22 -07002410 if (!SetSendCodec(channel, codec)) {
2411 LOG(LS_INFO) << "Failed to set codec " << codec.plname << " to bitrate "
2412 << bps << " bps.";
2413 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414 }
2415 return true;
2416 } else {
2417 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2418 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2419 // fixed bitrate then ignore.
2420 if (bps < codec.rate) {
2421 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2422 << " to bitrate " << bps << " bps"
2423 << ", requires at least " << codec.rate << " bps.";
2424 return false;
2425 }
2426 return true;
2427 }
2428}
2429
skvlad7a43d252016-03-22 15:32:27 -07002430void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2431 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2432 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2433 call_->SignalChannelNetworkState(
2434 webrtc::MediaType::AUDIO,
2435 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2436}
2437
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002439 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002440 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002441 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002442
solenberg85a04962015-10-27 03:35:21 -07002443 // Get SSRC and stats for each sender.
2444 RTC_DCHECK(info->senders.size() == 0);
2445 for (const auto& stream : send_streams_) {
2446 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002447 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002448 sinfo.add_ssrc(stats.local_ssrc);
2449 sinfo.bytes_sent = stats.bytes_sent;
2450 sinfo.packets_sent = stats.packets_sent;
2451 sinfo.packets_lost = stats.packets_lost;
2452 sinfo.fraction_lost = stats.fraction_lost;
2453 sinfo.codec_name = stats.codec_name;
2454 sinfo.ext_seqnum = stats.ext_seqnum;
2455 sinfo.jitter_ms = stats.jitter_ms;
2456 sinfo.rtt_ms = stats.rtt_ms;
2457 sinfo.audio_level = stats.audio_level;
2458 sinfo.aec_quality_min = stats.aec_quality_min;
2459 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2460 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2461 sinfo.echo_return_loss = stats.echo_return_loss;
2462 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002463 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002464 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 }
2466
solenberg85a04962015-10-27 03:35:21 -07002467 // Get SSRC and stats for each receiver.
2468 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002469 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002470 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2471 VoiceReceiverInfo rinfo;
2472 rinfo.add_ssrc(stats.remote_ssrc);
2473 rinfo.bytes_rcvd = stats.bytes_rcvd;
2474 rinfo.packets_rcvd = stats.packets_rcvd;
2475 rinfo.packets_lost = stats.packets_lost;
2476 rinfo.fraction_lost = stats.fraction_lost;
2477 rinfo.codec_name = stats.codec_name;
2478 rinfo.ext_seqnum = stats.ext_seqnum;
2479 rinfo.jitter_ms = stats.jitter_ms;
2480 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2481 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2482 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2483 rinfo.audio_level = stats.audio_level;
2484 rinfo.expand_rate = stats.expand_rate;
2485 rinfo.speech_expand_rate = stats.speech_expand_rate;
2486 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2487 rinfo.accelerate_rate = stats.accelerate_rate;
2488 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2489 rinfo.decoding_calls_to_silence_generator =
2490 stats.decoding_calls_to_silence_generator;
2491 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2492 rinfo.decoding_normal = stats.decoding_normal;
2493 rinfo.decoding_plc = stats.decoding_plc;
2494 rinfo.decoding_cng = stats.decoding_cng;
2495 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2496 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2497 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 }
2499
2500 return true;
2501}
2502
Tommif888bb52015-12-12 01:37:01 +01002503void WebRtcVoiceMediaChannel::SetRawAudioSink(
2504 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002505 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002506 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002507 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2508 << " " << (sink ? "(ptr)" : "NULL");
2509 if (ssrc == 0) {
2510 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002511 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002512 sink ? new ProxySink(sink.get()) : nullptr);
2513 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2514 }
2515 default_sink_ = std::move(sink);
2516 return;
2517 }
Tommif888bb52015-12-12 01:37:01 +01002518 const auto it = recv_streams_.find(ssrc);
2519 if (it == recv_streams_.end()) {
2520 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2521 return;
2522 }
deadbeef2d110be2016-01-13 12:00:26 -08002523 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002524}
2525
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002527 unsigned int ulevel = 0;
2528 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002529 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2530}
2531
Peter Boström0c4e06b2015-10-07 12:23:21 +02002532int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002533 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002534 const auto it = recv_streams_.find(ssrc);
2535 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002536 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002537 }
solenberg1ac56142015-10-13 03:58:19 -07002538 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002539}
2540
Peter Boström0c4e06b2015-10-07 12:23:21 +02002541int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002542 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002543 const auto it = send_streams_.find(ssrc);
2544 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002545 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002546 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002547 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548}
2549
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002550bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2551 if (playout) {
2552 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2553 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2554 LOG_RTCERR1(StartPlayout, channel);
2555 return false;
2556 }
2557 } else {
2558 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2559 engine()->voe()->base()->StopPlayout(channel);
2560 }
2561 return true;
2562}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563} // namespace cricket
2564
2565#endif // HAVE_WEBRTC_VOICE