blob: 6fe3d86fd98f086fe0622711c7769573d5276a1b [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() {
252 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
253 std::vector<AudioCodec> result;
254 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
255 // Change the sample rate of G722 to 8000 to match SDP.
256 MaybeFixupG722(&voe_codec, 8000);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000257 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100258 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000259 continue;
260 }
261
262 const CodecPref* pref = NULL;
tfarina5237aaf2015-11-10 23:44:30 -0800263 for (size_t j = 0; j < arraysize(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100264 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000265 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
266 kCodecPrefs[j].channels == voe_codec.channels) {
267 pref = &kCodecPrefs[j];
268 break;
269 }
270 }
271
272 if (pref) {
273 // Use the payload type that we've configured in our pref table;
274 // use the offset in our pref table to determine the sort order.
tfarina5237aaf2015-11-10 23:44:30 -0800275 AudioCodec codec(
276 pref->payload_type, voe_codec.plname, voe_codec.plfreq,
277 voe_codec.rate, voe_codec.channels,
278 static_cast<int>(arraysize(kCodecPrefs)) - (pref - kCodecPrefs));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000279 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100280 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000281 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000282 codec.bitrate = 0;
283 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100284 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000285 // Only add fmtp parameters that differ from the spec.
286 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
287 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000288 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000289 }
290 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
291 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000292 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000293 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000294 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800295 codec.AddFeedbackParam(
296 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000297
298 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000299 // when they can be set to values other than the default.
300 }
solenberg26c8c912015-11-27 04:00:25 -0800301 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000302 } else {
303 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
304 }
305 }
solenberg26c8c912015-11-27 04:00:25 -0800306 // Make sure they are in local preference order.
307 std::sort(result.begin(), result.end(), &AudioCodec::Preferable);
308 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000309 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000310
solenberg26c8c912015-11-27 04:00:25 -0800311 static bool ToCodecInst(const AudioCodec& in,
312 webrtc::CodecInst* out) {
313 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
314 // Change the sample rate of G722 to 8000 to match SDP.
315 MaybeFixupG722(&voe_codec, 8000);
316 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
317 voe_codec.rate, voe_codec.channels, 0);
318 bool multi_rate = IsCodecMultiRate(voe_codec);
319 // Allow arbitrary rates for ISAC to be specified.
320 if (multi_rate) {
321 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
322 codec.bitrate = 0;
323 }
324 if (codec.Matches(in)) {
325 if (out) {
326 // Fixup the payload type.
327 voe_codec.pltype = in.id;
328
329 // Set bitrate if specified.
330 if (multi_rate && in.bitrate != 0) {
331 voe_codec.rate = in.bitrate;
332 }
333
334 // Reset G722 sample rate to 16000 to match WebRTC.
335 MaybeFixupG722(&voe_codec, 16000);
336
337 // Apply codec-specific settings.
338 if (IsCodec(codec, kIsacCodecName)) {
339 // If ISAC and an explicit bitrate is not specified,
340 // enable auto bitrate adjustment.
341 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
342 }
343 *out = voe_codec;
344 }
345 return true;
346 }
347 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000348 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000349 }
solenberg26c8c912015-11-27 04:00:25 -0800350
351 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
352 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
353 if (IsCodec(codec, kCodecPrefs[i].name) &&
354 kCodecPrefs[i].clockrate == codec.plfreq) {
355 return kCodecPrefs[i].is_multi_rate;
356 }
357 }
358 return false;
359 }
360
361 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
362 // codec pacsize if it's valid, or we will pick the next smallest value we
363 // support.
364 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
365 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
366 for (const CodecPref& codec_pref : kCodecPrefs) {
367 if ((IsCodec(*codec, codec_pref.name) &&
368 codec_pref.clockrate == codec->plfreq) ||
369 IsCodec(*codec, kG722CodecName)) {
370 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
371 if (packet_size_ms) {
372 // Convert unit from milli-seconds to samples.
373 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
374 return true;
375 }
376 }
377 }
378 return false;
379 }
380
stefanba4c0e42016-02-04 04:12:24 -0800381 static const AudioCodec* GetPreferredCodec(
382 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800383 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800384 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800385 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800386 RTC_DCHECK(red_payload_type);
387 // Select the preferred send codec (the first non-telephone-event/CN codec).
388 for (const AudioCodec& codec : codecs) {
389 *red_payload_type = -1;
390 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
391 // Skip telephone-event/CN codec, which will be handled later.
392 continue;
393 }
394
395 // We'll use the first codec in the list to actually send audio data.
396 // Be sure to use the payload type requested by the remote side.
397 // "red", for RED audio, is a special case where the actual codec to be
398 // used is specified in params.
399 const AudioCodec* found_codec = &codec;
400 if (IsCodec(*found_codec, kRedCodecName)) {
401 // Parse out the RED parameters. If we fail, just ignore RED;
402 // we don't support all possible params/usage scenarios.
403 *red_payload_type = codec.id;
404 found_codec = GetRedSendCodec(*found_codec, codecs);
405 if (!found_codec) {
406 continue;
407 }
408 }
409 // Ignore codecs we don't know about. The negotiation step should prevent
410 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800411 webrtc::CodecInst voe_codec = {0};
412 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800413 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
414 continue;
415 }
solenberg72e29d22016-03-08 06:35:16 -0800416 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800417 return found_codec;
418 }
419 return nullptr;
420 }
421
solenberg26c8c912015-11-27 04:00:25 -0800422 private:
423 static const int kMaxNumPacketSize = 6;
424 struct CodecPref {
425 const char* name;
426 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800427 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800428 int payload_type;
429 bool is_multi_rate;
430 int packet_sizes_ms[kMaxNumPacketSize];
431 };
432 // Note: keep the supported packet sizes in ascending order.
433 static const CodecPref kCodecPrefs[12];
434
435 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
436 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
437 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
438 if (packet_size_ms && packet_size_ms <= ptime_ms) {
439 selected_packet_size_ms = packet_size_ms;
440 }
441 }
442 return selected_packet_size_ms;
443 }
444
445 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
446 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
447 // codec.
448 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
449 if (IsCodec(*voe_codec, kG722CodecName)) {
450 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
451 // has changed, and this special case is no longer needed.
452 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
453 voe_codec->plfreq = new_plfreq;
454 }
455 }
stefanba4c0e42016-02-04 04:12:24 -0800456
457 static const AudioCodec* GetRedSendCodec(
458 const AudioCodec& red_codec,
459 const std::vector<AudioCodec>& all_codecs) {
460 // Get the RED encodings from the parameter with no name. This may
461 // change based on what is discussed on the Jingle list.
462 // The encoding parameter is of the form "a/b"; we only support where
463 // a == b. Verify this and parse out the value into red_pt.
464 // If the parameter value is absent (as it will be until we wire up the
465 // signaling of this message), use the second codec specified (i.e. the
466 // one after "red") as the encoding parameter.
467 int red_pt = -1;
468 std::string red_params;
469 CodecParameterMap::const_iterator it = red_codec.params.find("");
470 if (it != red_codec.params.end()) {
471 red_params = it->second;
472 std::vector<std::string> red_pts;
473 if (rtc::split(red_params, '/', &red_pts) != 2 ||
474 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
475 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
476 return nullptr;
477 }
478 } else if (red_codec.params.empty()) {
479 LOG(LS_WARNING) << "RED params not present, using defaults";
480 if (all_codecs.size() > 1) {
481 red_pt = all_codecs[1].id;
482 }
483 }
484
485 // Try to find red_pt in |codecs|.
486 for (const AudioCodec& codec : all_codecs) {
487 if (codec.id == red_pt) {
488 return &codec;
489 }
490 }
491 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
492 return nullptr;
493 }
solenberg26c8c912015-11-27 04:00:25 -0800494};
495
496const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
497 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
498 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
499 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
500 // G722 should be advertised as 8000 Hz because of the RFC "bug".
501 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
502 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
503 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
504 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
505 { kCnCodecName, 32000, 1, 106, false, { } },
506 { kCnCodecName, 16000, 1, 105, false, { } },
507 { kCnCodecName, 8000, 1, 13, false, { } },
508 { kRedCodecName, 8000, 1, 127, false, { } },
509 { kDtmfCodecName, 8000, 1, 126, false, { } },
510};
511} // namespace {
512
513bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
514 webrtc::CodecInst* out) {
515 return WebRtcVoiceCodecs::ToCodecInst(in, out);
516}
517
518WebRtcVoiceEngine::WebRtcVoiceEngine()
519 : voe_wrapper_(new VoEWrapper()),
520 audio_state_(webrtc::AudioState::Create(MakeAudioStateConfig(voe()))) {
521 Construct();
522}
523
524WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper)
525 : voe_wrapper_(voe_wrapper) {
526 Construct();
527}
528
529void WebRtcVoiceEngine::Construct() {
530 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
531 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
532
533 signal_thread_checker_.DetachFromThread();
534 std::memset(&default_agc_config_, 0, sizeof(default_agc_config_));
solenberg246b8172015-12-08 09:50:23 -0800535 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
solenberg26c8c912015-11-27 04:00:25 -0800536
537 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
538 webrtc::Trace::SetTraceCallback(this);
539
540 // Load our audio codec list.
541 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000542}
543
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000544WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800545 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000546 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000547 if (adm_) {
548 voe_wrapper_.reset();
549 adm_->Release();
550 adm_ = NULL;
551 }
solenbergbd138382015-11-20 16:08:07 -0800552 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000553}
554
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000555bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
solenberg566ef242015-11-06 15:34:49 -0800556 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700557 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000558 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
559 bool res = InitInternal();
560 if (res) {
561 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
562 } else {
563 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
564 Terminate();
565 }
566 return res;
567}
568
569bool WebRtcVoiceEngine::InitInternal() {
solenberg566ef242015-11-06 15:34:49 -0800570 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg72e29d22016-03-08 06:35:16 -0800571 // Temporarily turn logging level up for the Init call.
solenbergbd138382015-11-20 16:08:07 -0800572 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800573 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000574 if (voe_wrapper_->base()->Init(adm_) == -1) {
575 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 return false;
577 }
solenbergbd138382015-11-20 16:08:07 -0800578 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000579
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000580 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800581 // calling ApplyOptions or the default will be overwritten.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000582 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
583 LOG_RTCERR0(GetAgcConfig);
584 return false;
585 }
586
solenberg0f7d2932016-01-15 01:40:39 -0800587 // Set default engine options.
588 {
589 AudioOptions options;
590 options.echo_cancellation = rtc::Optional<bool>(true);
591 options.auto_gain_control = rtc::Optional<bool>(true);
592 options.noise_suppression = rtc::Optional<bool>(true);
593 options.highpass_filter = rtc::Optional<bool>(true);
594 options.stereo_swapping = rtc::Optional<bool>(false);
595 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
596 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
597 options.typing_detection = rtc::Optional<bool>(true);
598 options.adjust_agc_delta = rtc::Optional<int>(0);
599 options.experimental_agc = rtc::Optional<bool>(false);
600 options.extended_filter_aec = rtc::Optional<bool>(false);
601 options.delay_agnostic_aec = rtc::Optional<bool>(false);
602 options.experimental_ns = rtc::Optional<bool>(false);
solenberg0f7d2932016-01-15 01:40:39 -0800603 if (!ApplyOptions(options)) {
604 return false;
605 }
606 }
607
solenberg72e29d22016-03-08 06:35:16 -0800608 // Print our codec list again for the call diagnostic log.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000609 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200610 for (const AudioCodec& codec : codecs_) {
611 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000612 }
613
solenberg246b8172015-12-08 09:50:23 -0800614 SetDefaultDevices();
615
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000616 initialized_ = true;
617 return true;
618}
619
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000620void WebRtcVoiceEngine::Terminate() {
solenberg566ef242015-11-06 15:34:49 -0800621 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000622 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
623 initialized_ = false;
624
625 StopAecDump();
626
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000627 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000628}
629
solenberg566ef242015-11-06 15:34:49 -0800630rtc::scoped_refptr<webrtc::AudioState>
631 WebRtcVoiceEngine::GetAudioState() const {
632 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
633 return audio_state_;
634}
635
nisse51542be2016-02-12 02:27:06 -0800636VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
637 webrtc::Call* call,
638 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200639 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800640 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800641 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000642}
643
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800645 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikac14f5ff2015-09-23 14:08:33 +0200646 LOG(LS_INFO) << "ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800647 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800648
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000649 // kEcConference is AEC with high suppression.
650 webrtc::EcModes ec_mode = webrtc::kEcConference;
651 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
652 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
653 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700654 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000655 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700656 << *options.aecm_generate_comfort_noise
657 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000658 }
659
kjellanderfcfc8042016-01-14 11:01:09 -0800660#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000661 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100662 options.echo_cancellation = rtc::Optional<bool>(false);
663 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200664 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000665#elif defined(ANDROID)
666 ec_mode = webrtc::kEcAecm;
667#endif
668
kjellanderfcfc8042016-01-14 11:01:09 -0800669#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000670 // Set the AGC mode for iOS as well despite disabling it above, to avoid
671 // unsupported configuration errors from webrtc.
672 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100673 options.typing_detection = rtc::Optional<bool>(false);
674 options.experimental_agc = rtc::Optional<bool>(false);
675 options.extended_filter_aec = rtc::Optional<bool>(false);
676 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000677#endif
678
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100679 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
680 // where the feature is not supported.
681 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800682#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700683 if (options.delay_agnostic_aec) {
684 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100685 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100686 options.echo_cancellation = rtc::Optional<bool>(true);
687 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100688 ec_mode = webrtc::kEcConference;
689 }
690 }
691#endif
692
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000693 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
694
kwiberg102c6a62015-10-30 02:47:38 -0700695 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000696 // Check if platform supports built-in EC. Currently only supported on
697 // Android and in combination with Java based audio layer.
698 // TODO(henrika): investigate possibility to support built-in EC also
699 // in combination with Open SL ES audio.
700 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200701 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200702 // Built-in EC exists on this device and use_delay_agnostic_aec is not
703 // overriding it. Enable/Disable it according to the echo_cancellation
704 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200705 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700706 *options.echo_cancellation && !use_delay_agnostic_aec;
Bjorn Volcker73f72102015-06-03 14:50:15 +0200707 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
708 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100709 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000710 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100711 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000712 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
713 }
714 }
kwiberg102c6a62015-10-30 02:47:38 -0700715 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
716 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000717 return false;
718 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700719 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200720 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000721 }
722#if !defined(ANDROID)
723 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700724 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
725 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000726 return false;
727 }
728#endif
729 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700730 bool cn = options.aecm_generate_comfort_noise.value_or(false);
731 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
732 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000733 return false;
734 }
735 }
736 }
737
kwiberg102c6a62015-10-30 02:47:38 -0700738 if (options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200739 const bool built_in_agc = voe_wrapper_->hw()->BuiltInAGCIsAvailable();
740 if (built_in_agc) {
kwiberg102c6a62015-10-30 02:47:38 -0700741 if (voe_wrapper_->hw()->EnableBuiltInAGC(*options.auto_gain_control) ==
742 0 &&
743 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200744 // Disable internal software AGC if built-in AGC is enabled,
745 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100746 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200747 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
748 }
749 }
kwiberg102c6a62015-10-30 02:47:38 -0700750 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
751 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000752 return false;
753 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700754 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
755 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000756 }
757 }
758
kwiberg102c6a62015-10-30 02:47:38 -0700759 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
760 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000761 // Override default_agc_config_. Generally, an unset option means "leave
762 // the VoE bits alone" in this function, so we want whatever is set to be
763 // stored as the new "default". If we didn't, then setting e.g.
764 // tx_agc_target_dbov would reset digital compression gain and limiter
765 // settings.
766 // Also, if we don't update default_agc_config_, then adjust_agc_delta
767 // would be an offset from the original values, and not whatever was set
768 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700769 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
770 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000771 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700772 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000773 default_agc_config_.digitalCompressionGaindB);
774 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700775 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000776 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
777 LOG_RTCERR3(SetAgcConfig,
778 default_agc_config_.targetLeveldBOv,
779 default_agc_config_.digitalCompressionGaindB,
780 default_agc_config_.limiterEnable);
781 return false;
782 }
783 }
784
kwiberg102c6a62015-10-30 02:47:38 -0700785 if (options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200786 const bool built_in_ns = voe_wrapper_->hw()->BuiltInNSIsAvailable();
787 if (built_in_ns) {
kwiberg102c6a62015-10-30 02:47:38 -0700788 if (voe_wrapper_->hw()->EnableBuiltInNS(*options.noise_suppression) ==
789 0 &&
790 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200791 // Disable internal software NS if built-in NS is enabled,
792 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100793 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200794 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
795 }
796 }
kwiberg102c6a62015-10-30 02:47:38 -0700797 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
798 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000799 return false;
800 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700801 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200802 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000803 }
804 }
805
kwiberg102c6a62015-10-30 02:47:38 -0700806 if (options.highpass_filter) {
807 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
808 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
809 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000810 return false;
811 }
812 }
813
kwiberg102c6a62015-10-30 02:47:38 -0700814 if (options.stereo_swapping) {
815 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
816 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
817 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
818 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000819 return false;
820 }
821 }
822
kwiberg102c6a62015-10-30 02:47:38 -0700823 if (options.audio_jitter_buffer_max_packets) {
824 LOG(LS_INFO) << "NetEq capacity is "
825 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200826 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700827 new webrtc::NetEqCapacityConfig(
828 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200829 }
830
kwiberg102c6a62015-10-30 02:47:38 -0700831 if (options.audio_jitter_buffer_fast_accelerate) {
832 LOG(LS_INFO) << "NetEq fast mode? "
833 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200834 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700835 new webrtc::NetEqFastAccelerate(
836 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200837 }
838
kwiberg102c6a62015-10-30 02:47:38 -0700839 if (options.typing_detection) {
840 LOG(LS_INFO) << "Typing detection is enabled? "
841 << *options.typing_detection;
842 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000843 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700844 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000845 }
846 }
847
kwiberg102c6a62015-10-30 02:47:38 -0700848 if (options.adjust_agc_delta) {
849 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
850 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000851 return false;
852 }
853 }
854
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000855 webrtc::Config config;
856
kwiberg102c6a62015-10-30 02:47:38 -0700857 if (options.delay_agnostic_aec)
858 delay_agnostic_aec_ = options.delay_agnostic_aec;
859 if (delay_agnostic_aec_) {
860 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700861 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700862 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100863 }
864
kwiberg102c6a62015-10-30 02:47:38 -0700865 if (options.extended_filter_aec) {
866 extended_filter_aec_ = options.extended_filter_aec;
867 }
868 if (extended_filter_aec_) {
869 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200870 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700871 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000872 }
873
kwiberg102c6a62015-10-30 02:47:38 -0700874 if (options.experimental_ns) {
875 experimental_ns_ = options.experimental_ns;
876 }
877 if (experimental_ns_) {
878 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000879 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700880 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000881 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000882
883 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
884 // returns NULL on audio_processing().
885 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
886 if (audioproc) {
887 audioproc->SetExtraOptions(config);
888 }
889
kwiberg102c6a62015-10-30 02:47:38 -0700890 if (options.recording_sample_rate) {
891 LOG(LS_INFO) << "Recording sample rate is "
892 << *options.recording_sample_rate;
893 if (voe_wrapper_->hw()->SetRecordingSampleRate(
894 *options.recording_sample_rate)) {
895 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000896 }
897 }
898
kwiberg102c6a62015-10-30 02:47:38 -0700899 if (options.playout_sample_rate) {
900 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
901 if (voe_wrapper_->hw()->SetPlayoutSampleRate(
902 *options.playout_sample_rate)) {
903 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000904 }
905 }
906
907 return true;
908}
909
solenberg246b8172015-12-08 09:50:23 -0800910void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800911 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800912#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800913 int in_id = kDefaultAudioDeviceId;
914 int out_id = kDefaultAudioDeviceId;
915 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
916 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000917
solenbergc1a1b352015-09-22 13:31:20 -0700918 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800919 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
920 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921 ret = false;
922 }
solenberg246b8172015-12-08 09:50:23 -0800923 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
924 if (ap) {
925 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 }
927
solenberg246b8172015-12-08 09:50:23 -0800928 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
929 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 ret = false;
931 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800934 LOG(LS_INFO) << "Set microphone to (id=" << in_id
935 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 }
kjellanderfcfc8042016-01-14 11:01:09 -0800937#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938}
939
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800941 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 unsigned int ulevel;
943 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
944 LOG_RTCERR1(GetSpeakerVolume, level);
945 return false;
946 }
947 *level = ulevel;
948 return true;
949}
950
951bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800952 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700953 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
955 LOG_RTCERR1(SetSpeakerVolume, level);
956 return false;
957 }
958 return true;
959}
960
961int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800962 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 unsigned int ulevel;
964 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
965 static_cast<int>(ulevel) : -1;
966}
967
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800969 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 return codecs_;
971}
972
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100973RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800974 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100975 RtpCapabilities capabilities;
976 capabilities.header_extensions.push_back(RtpHeaderExtension(
977 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
978 capabilities.header_extensions.push_back(
979 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
980 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800981 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
982 "Enabled") {
983 capabilities.header_extensions.push_back(RtpHeaderExtension(
984 kRtpTransportSequenceNumberHeaderExtension,
985 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
986 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100987 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988}
989
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800991 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992 return voe_wrapper_->error();
993}
994
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
996 int length) {
solenberg566ef242015-11-06 15:34:49 -0800997 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000998 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001000 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001002 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001004 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001006 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007
solenberg72e29d22016-03-08 06:35:16 -08001008 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 if (length < 72) {
1010 std::string msg(trace, length);
1011 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1012 LOG_V(sev) << msg;
1013 } else {
1014 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +02001015 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 }
1017}
1018
solenberg63b34542015-09-29 06:06:31 -07001019void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001020 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1021 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 channels_.push_back(channel);
1023}
1024
solenberg63b34542015-09-29 06:06:31 -07001025void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001026 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -07001027 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -08001028 RTC_DCHECK(it != channels_.end());
1029 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030}
1031
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032// Adjusts the default AGC target level by the specified delta.
1033// NB: If we start messing with other config fields, we'll want
1034// to save the current webrtc::AgcConfig as well.
1035bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -08001036 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 webrtc::AgcConfig config = default_agc_config_;
1038 config.targetLeveldBOv -= delta;
1039
1040 LOG(LS_INFO) << "Adjusting AGC level from default -"
1041 << default_agc_config_.targetLeveldBOv << "dB to -"
1042 << config.targetLeveldBOv << "dB";
1043
1044 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1045 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1046 return false;
1047 }
1048 return true;
1049}
1050
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001051bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
solenberg566ef242015-11-06 15:34:49 -08001052 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053 if (initialized_) {
1054 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1055 return false;
1056 }
1057 if (adm_) {
1058 adm_->Release();
1059 adm_ = NULL;
1060 }
1061 if (adm) {
1062 adm_ = adm;
1063 adm_->AddRef();
1064 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 return true;
1066}
1067
ivocd66b44d2016-01-15 03:06:36 -08001068bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
1069 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -08001070 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001071 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001072 if (!aec_dump_file_stream) {
1073 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001074 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001075 LOG(LS_WARNING) << "Could not close file.";
1076 return false;
1077 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001078 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001079 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1080 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001081 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001082 LOG_RTCERR0(StartDebugRecording);
1083 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001084 return false;
1085 }
1086 is_dumping_aec_ = true;
1087 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001088}
1089
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001091 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 if (!is_dumping_aec_) {
1093 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001094 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1095 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001096 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097 } else {
1098 is_dumping_aec_ = true;
1099 }
1100 }
1101}
1102
1103void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001104 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 if (is_dumping_aec_) {
1106 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001107 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 webrtc::AudioProcessing::kNoError) {
1109 LOG_RTCERR0(StopDebugRecording);
1110 }
1111 is_dumping_aec_ = false;
1112 }
1113}
1114
ivoc112a3d82015-10-16 02:22:18 -07001115bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001116 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001117 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1118 if (event_log) {
1119 return event_log->StartLogging(file);
1120 }
1121 LOG_RTCERR0(StartRtcEventLog);
1122 return false;
ivoc112a3d82015-10-16 02:22:18 -07001123}
1124
1125void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001126 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001127 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1128 if (event_log) {
1129 event_log->StopLogging();
1130 return;
1131 }
1132 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001133}
1134
solenberg0a617e22015-10-20 15:49:38 -07001135int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001136 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001137 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001138}
1139
solenbergc96df772015-10-21 13:01:53 -07001140class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001141 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001142 public:
solenbergc96df772015-10-21 13:01:53 -07001143 WebRtcAudioSendStream(int ch, webrtc::AudioTransport* voe_audio_transport,
solenberg3a941542015-11-16 07:34:50 -08001144 uint32_t ssrc, const std::string& c_name,
1145 const std::vector<webrtc::RtpExtension>& extensions,
1146 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001147 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001148 call_(call),
1149 config_(nullptr) {
solenberg85a04962015-10-27 03:35:21 -07001150 RTC_DCHECK_GE(ch, 0);
1151 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1152 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001153 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001154 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001155 config_.rtp.ssrc = ssrc;
1156 config_.rtp.c_name = c_name;
1157 config_.voe_channel_id = ch;
1158 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001159 }
solenberg3a941542015-11-16 07:34:50 -08001160
solenbergc96df772015-10-21 13:01:53 -07001161 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001162 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001163 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001164 call_->DestroyAudioSendStream(stream_);
1165 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001166
solenberg3a941542015-11-16 07:34:50 -08001167 void RecreateAudioSendStream(
1168 const std::vector<webrtc::RtpExtension>& extensions) {
1169 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1170 if (stream_) {
1171 call_->DestroyAudioSendStream(stream_);
1172 stream_ = nullptr;
1173 }
1174 config_.rtp.extensions = extensions;
1175 RTC_DCHECK(!stream_);
1176 stream_ = call_->CreateAudioSendStream(config_);
1177 RTC_CHECK(stream_);
1178 }
1179
solenberg8842c3e2016-03-11 03:06:41 -08001180 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001181 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1182 RTC_DCHECK(stream_);
1183 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1184 }
1185
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001186 void SetSend(bool send) {
1187 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1188 send_ = send;
1189 UpdateSendState();
1190 }
1191
solenberg3a941542015-11-16 07:34:50 -08001192 webrtc::AudioSendStream::Stats GetStats() const {
1193 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1194 RTC_DCHECK(stream_);
1195 return stream_->GetStats();
1196 }
1197
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001198 // Starts the sending by setting ourselves as a sink to the AudioSource to
1199 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001200 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001201 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001202 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001203 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001204 RTC_DCHECK(source);
1205 if (source_) {
1206 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001207 return;
1208 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001209 source->SetSink(this);
1210 source_ = source;
1211 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001212 }
1213
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001214 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001215 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001216 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001217 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001218 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001219 if (source_) {
1220 source_->SetSink(nullptr);
1221 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001222 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001223 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001224 }
1225
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001226 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001227 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001228 void OnData(const void* audio_data,
1229 int bits_per_sample,
1230 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001231 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001232 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001233 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001234 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001235 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001236 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001237 audio_data,
1238 bits_per_sample,
1239 sample_rate,
1240 number_of_channels,
1241 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001242 }
1243
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001244 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001245 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001246 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001247 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001248 // Set |source_| to nullptr to make sure no more callback will get into
1249 // the source.
1250 source_ = nullptr;
1251 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001252 }
1253
1254 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001255 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001256 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001257 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001258 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001259
1260 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001261 void UpdateSendState() {
1262 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1263 RTC_DCHECK(stream_);
1264 if (send_ && source_ != nullptr) {
1265 stream_->Start();
1266 } else { // !send || source_ = nullptr
1267 stream_->Stop();
1268 }
1269 }
1270
solenberg566ef242015-11-06 15:34:49 -08001271 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001272 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001273 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1274 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001275 webrtc::AudioSendStream::Config config_;
1276 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1277 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001278 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001279
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001280 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001281 // PeerConnection will make sure invalidating the pointer before the object
1282 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001283 AudioSource* source_ = nullptr;
1284 bool send_ = false;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001285
solenbergc96df772015-10-21 13:01:53 -07001286 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1287};
1288
1289class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1290 public:
stefanba4c0e42016-02-04 04:12:24 -08001291 WebRtcAudioReceiveStream(int ch,
1292 uint32_t remote_ssrc,
1293 uint32_t local_ssrc,
1294 bool use_transport_cc,
1295 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001296 const std::vector<webrtc::RtpExtension>& extensions,
1297 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001298 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001299 RTC_DCHECK_GE(ch, 0);
1300 RTC_DCHECK(call);
1301 config_.rtp.remote_ssrc = remote_ssrc;
1302 config_.rtp.local_ssrc = local_ssrc;
1303 config_.voe_channel_id = ch;
1304 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001305 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001306 }
solenbergc96df772015-10-21 13:01:53 -07001307
solenberg7add0582015-11-20 09:59:34 -08001308 ~WebRtcAudioReceiveStream() {
1309 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1310 call_->DestroyAudioReceiveStream(stream_);
1311 }
1312
1313 void RecreateAudioReceiveStream(
1314 const std::vector<webrtc::RtpExtension>& extensions) {
1315 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001316 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001317 }
stefanba4c0e42016-02-04 04:12:24 -08001318 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001319 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001320 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001321 }
1322
1323 webrtc::AudioReceiveStream::Stats GetStats() const {
1324 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1325 RTC_DCHECK(stream_);
1326 return stream_->GetStats();
1327 }
1328
1329 int channel() const {
1330 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1331 return config_.voe_channel_id;
1332 }
solenbergc96df772015-10-21 13:01:53 -07001333
kwiberg686a8ef2016-02-26 03:00:35 -08001334 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001335 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001336 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001337 }
1338
solenbergc96df772015-10-21 13:01:53 -07001339 private:
stefanba4c0e42016-02-04 04:12:24 -08001340 void RecreateAudioReceiveStream(
1341 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001342 const std::vector<webrtc::RtpExtension>& extensions) {
1343 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1344 if (stream_) {
1345 call_->DestroyAudioReceiveStream(stream_);
1346 stream_ = nullptr;
1347 }
1348 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001349 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001350 RTC_DCHECK(!stream_);
1351 stream_ = call_->CreateAudioReceiveStream(config_);
1352 RTC_CHECK(stream_);
1353 }
1354
1355 rtc::ThreadChecker worker_thread_checker_;
1356 webrtc::Call* call_ = nullptr;
1357 webrtc::AudioReceiveStream::Config config_;
1358 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1359 // configuration changes.
1360 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001361
1362 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001363};
1364
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001365WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001366 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001367 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001368 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001369 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001370 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001371 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001372 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001373 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374}
1375
1376WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001377 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001378 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001379 // TODO(solenberg): Should be able to delete the streams directly, without
1380 // going through RemoveNnStream(), once stream objects handle
1381 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001382 while (!send_streams_.empty()) {
1383 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001384 }
solenberg7add0582015-11-20 09:59:34 -08001385 while (!recv_streams_.empty()) {
1386 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 }
solenberg0a617e22015-10-20 15:49:38 -07001388 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389}
1390
nisse51542be2016-02-12 02:27:06 -08001391rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1392 return kAudioDscpValue;
1393}
1394
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001395bool WebRtcVoiceMediaChannel::SetSendParameters(
1396 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001397 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001398 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001399 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1400 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001401 // TODO(pthatcher): Refactor this to be more clean now that we have
1402 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001403
1404 if (!SetSendCodecs(params.codecs)) {
1405 return false;
1406 }
1407
solenberg7e4e01a2015-12-02 08:05:01 -08001408 if (!ValidateRtpExtensions(params.extensions)) {
1409 return false;
1410 }
1411 std::vector<webrtc::RtpExtension> filtered_extensions =
1412 FilterRtpExtensions(params.extensions,
1413 webrtc::RtpExtension::IsSupportedForAudio, true);
1414 if (send_rtp_extensions_ != filtered_extensions) {
1415 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001416 for (auto& it : send_streams_) {
1417 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1418 }
1419 }
1420
1421 if (!SetMaxSendBandwidth(params.max_bandwidth_bps)) {
1422 return false;
1423 }
1424 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001425}
1426
1427bool WebRtcVoiceMediaChannel::SetRecvParameters(
1428 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001429 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001430 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001431 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1432 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001433 // TODO(pthatcher): Refactor this to be more clean now that we have
1434 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001435
1436 if (!SetRecvCodecs(params.codecs)) {
1437 return false;
1438 }
1439
solenberg7e4e01a2015-12-02 08:05:01 -08001440 if (!ValidateRtpExtensions(params.extensions)) {
1441 return false;
1442 }
1443 std::vector<webrtc::RtpExtension> filtered_extensions =
1444 FilterRtpExtensions(params.extensions,
1445 webrtc::RtpExtension::IsSupportedForAudio, false);
1446 if (recv_rtp_extensions_ != filtered_extensions) {
1447 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001448 for (auto& it : recv_streams_) {
1449 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1450 }
1451 }
solenberg7add0582015-11-20 09:59:34 -08001452 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001453}
1454
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001456 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457 LOG(LS_INFO) << "Setting voice channel options: "
1458 << options.ToString();
1459
1460 // We retain all of the existing options, and apply the given ones
1461 // on top. This means there is no way to "clear" options such that
1462 // they go back to the engine default.
1463 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001464 if (!engine()->ApplyOptions(options_)) {
1465 LOG(LS_WARNING) <<
1466 "Failed to apply engine options during channel SetOptions.";
1467 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 LOG(LS_INFO) << "Set voice channel options. Current options: "
1470 << options_.ToString();
1471 return true;
1472}
1473
1474bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1475 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001476 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001479 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001480
1481 if (!VerifyUniquePayloadTypes(codecs)) {
1482 LOG(LS_ERROR) << "Codec payload types overlap.";
1483 return false;
1484 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485
1486 std::vector<AudioCodec> new_codecs;
1487 // Find all new codecs. We allow adding new codecs but don't allow changing
1488 // the payload type of codecs that is already configured since we might
1489 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001490 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001492 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1493 if (old_codec.id != codec.id) {
1494 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495 return false;
1496 }
1497 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001498 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 }
1500 }
1501 if (new_codecs.empty()) {
1502 // There are no new codecs to configure. Already configured codecs are
1503 // never removed.
1504 return true;
1505 }
1506
1507 if (playout_) {
1508 // Receive codecs can not be changed while playing. So we temporarily
1509 // pause playout.
1510 PausePlayout();
1511 }
1512
solenberg26c8c912015-11-27 04:00:25 -08001513 bool result = true;
1514 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001515 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001516 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1517 LOG(LS_INFO) << ToString(codec);
1518 voe_codec.pltype = codec.id;
1519 for (const auto& ch : recv_streams_) {
1520 if (engine()->voe()->codec()->SetRecPayloadType(
1521 ch.second->channel(), voe_codec) == -1) {
1522 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1523 ToString(voe_codec));
1524 result = false;
1525 }
1526 }
1527 } else {
1528 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1529 result = false;
1530 break;
1531 }
1532 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001533 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001534 recv_codecs_ = codecs;
1535 }
1536
1537 if (desired_playout_ && !playout_) {
1538 ResumePlayout();
1539 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001540 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001541}
1542
solenberg72e29d22016-03-08 06:35:16 -08001543// Utility function called from SetSendParameters() to extract current send
1544// codec settings from the given list of codecs (originally from SDP). Both send
1545// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001546bool WebRtcVoiceMediaChannel::SetSendCodecs(
1547 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001548 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001549 // TODO(solenberg): Validate input - that payload types don't overlap, are
1550 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001551 // redundant codecs etc - the same way it is done for
1552 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001553
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001554 // Find the DTMF telephone event "codec" payload type.
1555 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001556 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001557 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001558 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1559 return false;
1560 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001561 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1562 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001563 }
1564 }
1565
solenberg72e29d22016-03-08 06:35:16 -08001566 // Scan through the list to figure out the codec to use for sending, along
1567 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1568 // parameters.
1569 {
1570 SendCodecSpec send_codec_spec;
1571 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1572
1573 // Find send codec (the first non-telephone-event/CN codec).
1574 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1575 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1576 if (!codec) {
1577 LOG(LS_WARNING) << "Received empty list of codecs.";
1578 return false;
1579 }
1580
1581 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1582
1583 // This condition is apparently here because Opus does not support RED and
1584 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1585 // such limitations.
1586 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1587 if (send_codec_spec.red_payload_type == -1) {
1588 send_codec_spec.nack_enabled = HasNack(*codec);
1589 // For Opus as the send codec, we are to determine inband FEC, maximum
1590 // playback rate, and opus internal dtx.
1591 if (IsCodec(*codec, kOpusCodecName)) {
1592 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1593 &send_codec_spec.enable_codec_fec,
1594 &send_codec_spec.opus_max_playback_rate,
1595 &send_codec_spec.enable_opus_dtx);
1596 }
1597
1598 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1599 int ptime_ms = 0;
1600 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1601 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1602 &send_codec_spec.codec_inst, ptime_ms)) {
1603 LOG(LS_WARNING) << "Failed to set packet size for codec "
1604 << send_codec_spec.codec_inst.plname;
1605 return false;
1606 }
1607 }
1608 }
1609
1610 // Loop through the codecs list again to find the CN codec.
1611 // TODO(solenberg): Break out into a separate function?
1612 for (const AudioCodec& codec : codecs) {
1613 // Ignore codecs we don't know about. The negotiation step should prevent
1614 // this, but double-check to be sure.
1615 webrtc::CodecInst voe_codec = {0};
1616 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1617 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1618 continue;
1619 }
1620
1621 if (IsCodec(codec, kCnCodecName)) {
1622 // Turn voice activity detection/comfort noise on if supported.
1623 // Set the wideband CN payload type appropriately.
1624 // (narrowband always uses the static payload type 13).
1625 int cng_plfreq = -1;
1626 switch (codec.clockrate) {
1627 case 8000:
1628 case 16000:
1629 case 32000:
1630 cng_plfreq = codec.clockrate;
1631 break;
1632 default:
1633 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1634 << " not supported.";
1635 continue;
1636 }
1637 send_codec_spec.cng_payload_type = codec.id;
1638 send_codec_spec.cng_plfreq = cng_plfreq;
1639 break;
1640 }
1641 }
1642
1643 // Latch in the new state.
1644 send_codec_spec_ = std::move(send_codec_spec);
1645 }
1646
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001647 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001648 for (const auto& ch : send_streams_) {
solenberg72e29d22016-03-08 06:35:16 -08001649 if (!SetSendCodecs(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001650 return false;
1651 }
1652 }
1653
solenberg72e29d22016-03-08 06:35:16 -08001654 // Set nack status on receive channels.
1655 if (!send_streams_.empty()) {
1656 for (const auto& kv : recv_streams_) {
1657 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1658 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001659 }
solenberg0a617e22015-10-20 15:49:38 -07001660
stefanba4c0e42016-02-04 04:12:24 -08001661 // Check if the transport cc feedback has changed on the preferred send codec,
1662 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001663 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1664 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1665 "codec has changed.";
1666 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1667 for (auto& kv : recv_streams_) {
1668 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1669 }
1670 }
1671
1672 return true;
1673}
1674
1675// Apply current codec settings to a single voe::Channel used for sending.
1676bool WebRtcVoiceMediaChannel::SetSendCodecs(int channel) {
1677 // Disable VAD, FEC, and RED unless we know the other side wants them.
1678 engine()->voe()->codec()->SetVADStatus(channel, false);
1679 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1680 engine()->voe()->rtp()->SetREDStatus(channel, false);
1681 engine()->voe()->codec()->SetFECStatus(channel, false);
1682
1683 if (send_codec_spec_.red_payload_type != -1) {
1684 // Enable redundant encoding of the specified codec. Treat any
1685 // failure as a fatal internal error.
1686 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1687 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1688 send_codec_spec_.red_payload_type) == -1) {
1689 LOG_RTCERR3(SetREDStatus, channel, true,
1690 send_codec_spec_.red_payload_type);
1691 return false;
1692 }
1693 }
1694
1695 SetNack(channel, send_codec_spec_.nack_enabled);
1696
1697 // Set the codec immediately, since SetVADStatus() depends on whether
1698 // the current codec is mono or stereo.
1699 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1700 return false;
1701 }
1702
1703 // FEC should be enabled after SetSendCodec.
1704 if (send_codec_spec_.enable_codec_fec) {
1705 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1706 << channel;
1707 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1708 // Enable codec internal FEC. Treat any failure as fatal internal error.
1709 LOG_RTCERR2(SetFECStatus, channel, true);
1710 return false;
1711 }
1712 }
1713
1714 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1715 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1716 // send codec has to be Opus.
1717
1718 // Set Opus internal DTX.
1719 LOG(LS_INFO) << "Attempt to "
1720 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1721 << " Opus DTX on channel "
1722 << channel;
1723 if (engine()->voe()->codec()->SetOpusDtx(channel,
1724 send_codec_spec_.enable_opus_dtx)) {
1725 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1726 return false;
1727 }
1728
1729 // If opus_max_playback_rate <= 0, the default maximum playback rate
1730 // (48 kHz) will be used.
1731 if (send_codec_spec_.opus_max_playback_rate > 0) {
1732 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1733 << send_codec_spec_.opus_max_playback_rate
1734 << " Hz on channel "
1735 << channel;
1736 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1737 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1738 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1739 send_codec_spec_.opus_max_playback_rate);
1740 return false;
stefanba4c0e42016-02-04 04:12:24 -08001741 }
1742 }
1743 }
1744
solenberg72e29d22016-03-08 06:35:16 -08001745 if (send_bitrate_setting_) {
1746 SetSendBitrateInternal(send_bitrate_bps_);
1747 }
1748
1749 // Set the CN payloadtype and the VAD status.
1750 if (send_codec_spec_.cng_payload_type != -1) {
1751 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1752 if (send_codec_spec_.cng_plfreq != 8000) {
1753 webrtc::PayloadFrequencies cn_freq;
1754 switch (send_codec_spec_.cng_plfreq) {
1755 case 16000:
1756 cn_freq = webrtc::kFreq16000Hz;
1757 break;
1758 case 32000:
1759 cn_freq = webrtc::kFreq32000Hz;
1760 break;
1761 default:
1762 RTC_NOTREACHED();
1763 return false;
1764 }
1765 if (engine()->voe()->codec()->SetSendCNPayloadType(
1766 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1767 LOG_RTCERR3(SetSendCNPayloadType, channel,
1768 send_codec_spec_.cng_payload_type, cn_freq);
1769 // TODO(ajm): This failure condition will be removed from VoE.
1770 // Restore the return here when we update to a new enough webrtc.
1771 //
1772 // Not returning false because the SetSendCNPayloadType will fail if
1773 // the channel is already sending.
1774 // This can happen if the remote description is applied twice, for
1775 // example in the case of ROAP on top of JSEP, where both side will
1776 // send the offer.
1777 }
1778 }
1779
1780 // Only turn on VAD if we have a CN payload type that matches the
1781 // clockrate for the codec we are going to use.
1782 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1783 send_codec_spec_.codec_inst.channels == 1) {
1784 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1785 // interaction between VAD and Opus FEC.
1786 LOG(LS_INFO) << "Enabling VAD";
1787 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1788 LOG_RTCERR2(SetVADStatus, channel, true);
1789 return false;
1790 }
1791 }
1792 }
solenberg0a617e22015-10-20 15:49:38 -07001793 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001794}
1795
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001796void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001798 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1800 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001801 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1803 }
1804}
1805
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001807 int channel, const webrtc::CodecInst& send_codec) {
1808 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1809 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1810
solenberg72e29d22016-03-08 06:35:16 -08001811 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001812 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1813 (send_codec == current_codec)) {
1814 // Codec is already configured, we can return without setting it again.
1815 return true;
1816 }
1817
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001818 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1819 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return false;
1821 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 return true;
1823}
1824
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1826 desired_playout_ = playout;
1827 return ChangePlayout(desired_playout_);
1828}
1829
1830bool WebRtcVoiceMediaChannel::PausePlayout() {
1831 return ChangePlayout(false);
1832}
1833
1834bool WebRtcVoiceMediaChannel::ResumePlayout() {
1835 return ChangePlayout(desired_playout_);
1836}
1837
1838bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001839 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001840 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841 if (playout_ == playout) {
1842 return true;
1843 }
1844
solenberg7add0582015-11-20 09:59:34 -08001845 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001846 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001847 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001848 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001849 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 }
1851 }
solenberg1ac56142015-10-13 03:58:19 -07001852 playout_ = playout;
1853 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854}
1855
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001856void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001857 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001859 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 }
1861
solenberg246b8172015-12-08 09:50:23 -08001862 // Apply channel specific options when channel is enabled for sending.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001863 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001864 engine()->ApplyOptions(options_);
1865 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001867 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001868 for (auto& kv : send_streams_) {
1869 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001871
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001872 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873}
1874
Peter Boström0c4e06b2015-10-07 12:23:21 +02001875bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1876 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001877 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001878 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001879 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001880 // TODO(solenberg): The state change should be fully rolled back if any one of
1881 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001882 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001883 return false;
1884 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001885 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001886 return false;
1887 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001888 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001889 return SetOptions(*options);
1890 }
1891 return true;
1892}
1893
solenberg0a617e22015-10-20 15:49:38 -07001894int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1895 int id = engine()->CreateVoEChannel();
1896 if (id == -1) {
1897 LOG_RTCERR0(CreateVoEChannel);
1898 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001899 }
solenberg0a617e22015-10-20 15:49:38 -07001900 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1901 LOG_RTCERR2(RegisterExternalTransport, id, this);
1902 engine()->voe()->base()->DeleteChannel(id);
1903 return -1;
1904 }
1905 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001906}
1907
solenberg7add0582015-11-20 09:59:34 -08001908bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001909 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1910 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1911 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001912 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1913 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 return false;
1915 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001916 return true;
1917}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001918
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001919bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001920 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001921 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001922 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1923
1924 uint32_t ssrc = sp.first_ssrc();
1925 RTC_DCHECK(0 != ssrc);
1926
1927 if (GetSendChannelId(ssrc) != -1) {
1928 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001929 return false;
1930 }
1931
solenberg0a617e22015-10-20 15:49:38 -07001932 // Create a new channel for sending audio data.
1933 int channel = CreateVoEChannel();
1934 if (channel == -1) {
1935 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001936 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001937
solenbergc96df772015-10-21 13:01:53 -07001938 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001939 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001940 webrtc::AudioTransport* audio_transport =
1941 engine()->voe()->base()->audio_transport();
solenberg3a941542015-11-16 07:34:50 -08001942 send_streams_.insert(std::make_pair(ssrc, new WebRtcAudioSendStream(
1943 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001944
solenberg0a617e22015-10-20 15:49:38 -07001945 // Set the current codecs to be used for the new channel. We need to do this
1946 // after adding the channel to send_channels_, because of how max bitrate is
1947 // currently being configured by SetSendCodec().
solenberg72e29d22016-03-08 06:35:16 -08001948 if (HasSendCodec() && !SetSendCodecs(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001949 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001950 return false;
1951 }
1952
1953 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001954 // the first send channel make sure that all the receive channels are updated
1955 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001956 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001957 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001958 for (const auto& stream : recv_streams_) {
1959 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001960 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001961 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001962 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001963 }
solenberg0a617e22015-10-20 15:49:38 -07001964 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1965 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1966 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001967 }
1968 }
1969
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001970 send_streams_[ssrc]->SetSend(send_);
1971 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001972}
1973
Peter Boström0c4e06b2015-10-07 12:23:21 +02001974bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001975 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001976 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001977 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1978
solenbergc96df772015-10-21 13:01:53 -07001979 auto it = send_streams_.find(ssrc);
1980 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001981 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1982 << " which doesn't exist.";
1983 return false;
1984 }
1985
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001986 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001987
solenberg7add0582015-11-20 09:59:34 -08001988 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001989 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001990 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1991 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001992 delete it->second;
1993 send_streams_.erase(it);
1994 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001995 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001996 }
solenbergc96df772015-10-21 13:01:53 -07001997 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001998 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07001999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002000 return true;
2001}
2002
2003bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002004 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002005 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002006 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2007
solenberg0b675462015-10-09 01:37:09 -07002008 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002009 return false;
2010 }
2011
solenberg7add0582015-11-20 09:59:34 -08002012 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002013 if (ssrc == 0) {
2014 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2015 return false;
2016 }
2017
solenberg1ac56142015-10-13 03:58:19 -07002018 // Remove the default receive stream if one had been created with this ssrc;
2019 // we'll recreate it then.
2020 if (IsDefaultRecvStream(ssrc)) {
2021 RemoveRecvStream(ssrc);
2022 }
solenberg0b675462015-10-09 01:37:09 -07002023
solenberg7add0582015-11-20 09:59:34 -08002024 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002025 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 return false;
2027 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002028
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002030 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 return false;
2033 }
Minyue2013aec2015-05-13 14:14:42 +02002034
solenberg1ac56142015-10-13 03:58:19 -07002035 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002036 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2037 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2038 voe_codec.pltype = -1;
2039 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2040 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2041 DeleteVoEChannel(channel);
2042 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043 }
2044 }
2045
solenberg1ac56142015-10-13 03:58:19 -07002046 // Only enable those configured for this channel.
2047 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002048 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002049 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002050 voe_codec.pltype = codec.id;
2051 if (engine()->voe()->codec()->SetRecPayloadType(
2052 channel, voe_codec) == -1) {
2053 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002054 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002055 return false;
2056 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002057 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058 }
solenberg8fb30c32015-10-13 03:06:58 -07002059
solenberg7add0582015-11-20 09:59:34 -08002060 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2061 if (send_channel != -1) {
2062 // Associate receive channel with first send channel (so the receive channel
2063 // can obtain RTT from the send channel)
2064 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2065 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2066 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002067 }
2068
stefanba4c0e42016-02-04 04:12:24 -08002069 recv_streams_.insert(std::make_pair(
2070 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002071 recv_transport_cc_enabled_,
2072 sp.sync_label, recv_rtp_extensions_,
2073 call_)));
solenberg7add0582015-11-20 09:59:34 -08002074
solenberg72e29d22016-03-08 06:35:16 -08002075 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002076 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002077
solenberg1ac56142015-10-13 03:58:19 -07002078 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079}
2080
Peter Boström0c4e06b2015-10-07 12:23:21 +02002081bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002082 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002083 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002084 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2085
solenberg7add0582015-11-20 09:59:34 -08002086 const auto it = recv_streams_.find(ssrc);
2087 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002088 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2089 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002090 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002091 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002092
solenberg1ac56142015-10-13 03:58:19 -07002093 // Deregister default channel, if that's the one being destroyed.
2094 if (IsDefaultRecvStream(ssrc)) {
2095 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002096 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002097
solenberg7add0582015-11-20 09:59:34 -08002098 const int channel = it->second->channel();
2099
2100 // Clean up and delete the receive stream+channel.
2101 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002102 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002103 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002104 delete it->second;
2105 recv_streams_.erase(it);
2106 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107}
2108
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002109bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2110 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002111 auto it = send_streams_.find(ssrc);
2112 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002113 if (source) {
2114 // Return an error if trying to set a valid source with an invalid ssrc.
2115 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002116 return false;
2117 }
2118
2119 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002120 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002121 }
2122
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002123 if (source) {
2124 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002125 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002126 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002127 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 return true;
2130}
2131
2132bool WebRtcVoiceMediaChannel::GetActiveStreams(
2133 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002134 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002136 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002137 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002139 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 }
2141 }
2142 return true;
2143}
2144
2145int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002146 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002147 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002148 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002149 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 }
2151 return highest;
2152}
2153
2154int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2155 int ret;
2156 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2157 // In case of error, log the info and continue
2158 LOG_RTCERR0(TimeSinceLastTyping);
2159 ret = -1;
2160 } else {
2161 ret *= 1000; // We return ms, webrtc returns seconds.
2162 }
2163 return ret;
2164}
2165
2166void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2167 int cost_per_typing, int reporting_threshold, int penalty_decay,
2168 int type_event_delay) {
2169 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2170 time_window, cost_per_typing,
2171 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2172 // In case of error, log the info and continue
2173 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2174 cost_per_typing, reporting_threshold, penalty_decay,
2175 type_event_delay);
2176 }
2177}
2178
solenberg4bac9c52015-10-09 02:32:53 -07002179bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002180 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002181 if (ssrc == 0) {
2182 default_recv_volume_ = volume;
2183 if (default_recv_ssrc_ == -1) {
2184 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 }
solenberg1ac56142015-10-13 03:58:19 -07002186 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2187 }
2188 int ch_id = GetReceiveChannelId(ssrc);
2189 if (ch_id < 0) {
2190 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2191 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002192 }
2193
solenberg1ac56142015-10-13 03:58:19 -07002194 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2195 volume)) {
2196 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2197 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 }
solenberg1ac56142015-10-13 03:58:19 -07002199 LOG(LS_INFO) << "SetOutputVolume to " << volume
2200 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 return true;
2202}
2203
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002204bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002205 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206}
2207
solenberg1d63dd02015-12-02 12:35:09 -08002208bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2209 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002210 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002211 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2212 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 return false;
2214 }
2215
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002216 // Figure out which WebRtcAudioSendStream to send the event on.
2217 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2218 if (it == send_streams_.end()) {
2219 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002220 return false;
2221 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002222 if (event < kMinTelephoneEventCode ||
2223 event > kMaxTelephoneEventCode) {
2224 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002225 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002227 if (duration < kMinTelephoneEventDuration ||
2228 duration > kMaxTelephoneEventDuration) {
2229 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2230 return false;
2231 }
2232 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002233}
2234
wu@webrtc.orga9890802013-12-13 00:21:03 +00002235void WebRtcVoiceMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002236 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002237 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002238
solenberg1ac56142015-10-13 03:58:19 -07002239 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002240 if (!GetRtpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg1ac56142015-10-13 03:58:19 -07002241 return;
2242 }
2243
solenberg7e63ef02015-11-20 00:19:43 -08002244 // If we don't have a default channel, and the SSRC is unknown, create a
2245 // default channel.
2246 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002247 StreamParams sp;
2248 sp.ssrcs.push_back(ssrc);
2249 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2250 if (!AddRecvStream(sp)) {
2251 LOG(LS_WARNING) << "Could not create default receive stream.";
2252 return;
2253 }
2254 default_recv_ssrc_ = ssrc;
2255 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002256 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002257 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002258 new ProxySink(default_sink_.get()));
2259 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2260 }
solenberg1ac56142015-10-13 03:58:19 -07002261 }
2262
2263 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002264 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2265 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002266 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2267 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002268 packet->cdata(), packet->size(), webrtc_packet_time);
solenberg1ac56142015-10-13 03:58:19 -07002269 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002270 // If the SSRC is unknown here, route it to the default channel, if we have
2271 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2272 if (default_recv_ssrc_ == -1) {
2273 return;
2274 } else {
2275 ssrc = default_recv_ssrc_;
2276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277 }
2278
solenberg1ac56142015-10-13 03:58:19 -07002279 // Find the channel to send this packet to. It must exist since webrtc::Call
2280 // was able to demux the packet.
2281 int channel = GetReceiveChannelId(ssrc);
2282 RTC_DCHECK(channel != -1);
2283
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002285 engine()->voe()->network()->ReceivedRTPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002286 channel, packet->cdata(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002287}
2288
wu@webrtc.orga9890802013-12-13 00:21:03 +00002289void WebRtcVoiceMediaChannel::OnRtcpReceived(
jbaucheec21bd2016-03-20 06:15:43 -07002290 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002291 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002292
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002293 // Forward packet to Call as well.
2294 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2295 packet_time.not_before);
2296 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
jbaucheec21bd2016-03-20 06:15:43 -07002297 packet->cdata(), packet->size(), webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002298
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002299 // Sending channels need all RTCP packets with feedback information.
2300 // Even sender reports can contain attached report blocks.
2301 // Receiving channels need sender reports in order to create
2302 // correct receiver reports.
2303 int type = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002304 if (!GetRtcpType(packet->cdata(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002305 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2306 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 }
2308
solenberg0b675462015-10-09 01:37:09 -07002309 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002310 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002311 uint32_t ssrc = 0;
jbaucheec21bd2016-03-20 06:15:43 -07002312 if (!GetRtcpSsrc(packet->cdata(), packet->size(), &ssrc)) {
solenberg0b675462015-10-09 01:37:09 -07002313 return;
2314 }
2315 int recv_channel_id = GetReceiveChannelId(ssrc);
2316 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002317 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002318 recv_channel_id, packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002319 }
2320 }
2321
2322 // SR may continue RR and any RR entry may correspond to any one of the send
2323 // channels. So all RTCP packets must be forwarded all send channels. VoE
2324 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002325 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002326 engine()->voe()->network()->ReceivedRTCPPacket(
jbaucheec21bd2016-03-20 06:15:43 -07002327 ch.second->channel(), packet->cdata(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002328 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329}
2330
Honghai Zhangcc411c02016-03-29 17:27:21 -07002331void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2332 const std::string& transport_name,
2333 const NetworkRoute& network_route) {
2334 // TODO(honghaiz): uncomment this once the function in call is implemented.
2335 // call_->OnNetworkRouteChanged(transport_name, network_route);
2336}
2337
Peter Boström0c4e06b2015-10-07 12:23:21 +02002338bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002339 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002340 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002341 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002342 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2343 return false;
2344 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002345 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2346 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 return false;
2348 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002349 // We set the AGC to mute state only when all the channels are muted.
2350 // This implementation is not ideal, instead we should signal the AGC when
2351 // the mic channel is muted/unmuted. We can't do it today because there
2352 // is no good way to know which stream is mapping to the mic channel.
2353 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002354 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002355 if (!all_muted) {
2356 break;
2357 }
2358 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002359 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002360 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002361 return false;
2362 }
2363 }
2364
2365 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002366 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002367 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002368 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002369 return true;
2370}
2371
minyue@webrtc.org26236952014-10-29 02:27:08 +00002372// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2373// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002374bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002375 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
minyue@webrtc.org26236952014-10-29 02:27:08 +00002376 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002377}
2378
minyue@webrtc.org26236952014-10-29 02:27:08 +00002379bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2380 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002381
minyue@webrtc.org26236952014-10-29 02:27:08 +00002382 send_bitrate_setting_ = true;
2383 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002384
solenberg72e29d22016-03-08 06:35:16 -08002385 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002386 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002387 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002388 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389 }
2390
minyue@webrtc.org26236952014-10-29 02:27:08 +00002391 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002392 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2393 // SetMaxSendBandwith(0), the second call removes the previous limit.
2394 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395 return true;
2396
solenberg72e29d22016-03-08 06:35:16 -08002397 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002398 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399
2400 if (is_multi_rate) {
2401 // If codec is multi-rate then just set the bitrate.
2402 codec.rate = bps;
solenbergc96df772015-10-21 13:01:53 -07002403 for (const auto& ch : send_streams_) {
solenberg0a617e22015-10-20 15:49:38 -07002404 if (!SetSendCodec(ch.second->channel(), codec)) {
2405 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2406 << " to bitrate " << bps << " bps.";
2407 return false;
2408 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002409 }
2410 return true;
2411 } else {
2412 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2413 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2414 // fixed bitrate then ignore.
2415 if (bps < codec.rate) {
2416 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2417 << " to bitrate " << bps << " bps"
2418 << ", requires at least " << codec.rate << " bps.";
2419 return false;
2420 }
2421 return true;
2422 }
2423}
2424
skvlad7a43d252016-03-22 15:32:27 -07002425void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2426 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2427 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2428 call_->SignalChannelNetworkState(
2429 webrtc::MediaType::AUDIO,
2430 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2431}
2432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002434 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002435 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002436 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002437
solenberg85a04962015-10-27 03:35:21 -07002438 // Get SSRC and stats for each sender.
2439 RTC_DCHECK(info->senders.size() == 0);
2440 for (const auto& stream : send_streams_) {
2441 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002442 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002443 sinfo.add_ssrc(stats.local_ssrc);
2444 sinfo.bytes_sent = stats.bytes_sent;
2445 sinfo.packets_sent = stats.packets_sent;
2446 sinfo.packets_lost = stats.packets_lost;
2447 sinfo.fraction_lost = stats.fraction_lost;
2448 sinfo.codec_name = stats.codec_name;
2449 sinfo.ext_seqnum = stats.ext_seqnum;
2450 sinfo.jitter_ms = stats.jitter_ms;
2451 sinfo.rtt_ms = stats.rtt_ms;
2452 sinfo.audio_level = stats.audio_level;
2453 sinfo.aec_quality_min = stats.aec_quality_min;
2454 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2455 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2456 sinfo.echo_return_loss = stats.echo_return_loss;
2457 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002458 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 }
2461
solenberg85a04962015-10-27 03:35:21 -07002462 // Get SSRC and stats for each receiver.
2463 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002464 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002465 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2466 VoiceReceiverInfo rinfo;
2467 rinfo.add_ssrc(stats.remote_ssrc);
2468 rinfo.bytes_rcvd = stats.bytes_rcvd;
2469 rinfo.packets_rcvd = stats.packets_rcvd;
2470 rinfo.packets_lost = stats.packets_lost;
2471 rinfo.fraction_lost = stats.fraction_lost;
2472 rinfo.codec_name = stats.codec_name;
2473 rinfo.ext_seqnum = stats.ext_seqnum;
2474 rinfo.jitter_ms = stats.jitter_ms;
2475 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2476 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2477 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2478 rinfo.audio_level = stats.audio_level;
2479 rinfo.expand_rate = stats.expand_rate;
2480 rinfo.speech_expand_rate = stats.speech_expand_rate;
2481 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2482 rinfo.accelerate_rate = stats.accelerate_rate;
2483 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2484 rinfo.decoding_calls_to_silence_generator =
2485 stats.decoding_calls_to_silence_generator;
2486 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2487 rinfo.decoding_normal = stats.decoding_normal;
2488 rinfo.decoding_plc = stats.decoding_plc;
2489 rinfo.decoding_cng = stats.decoding_cng;
2490 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2491 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2492 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 }
2494
2495 return true;
2496}
2497
Tommif888bb52015-12-12 01:37:01 +01002498void WebRtcVoiceMediaChannel::SetRawAudioSink(
2499 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002500 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002501 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002502 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2503 << " " << (sink ? "(ptr)" : "NULL");
2504 if (ssrc == 0) {
2505 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002506 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002507 sink ? new ProxySink(sink.get()) : nullptr);
2508 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2509 }
2510 default_sink_ = std::move(sink);
2511 return;
2512 }
Tommif888bb52015-12-12 01:37:01 +01002513 const auto it = recv_streams_.find(ssrc);
2514 if (it == recv_streams_.end()) {
2515 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2516 return;
2517 }
deadbeef2d110be2016-01-13 12:00:26 -08002518 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002519}
2520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002522 unsigned int ulevel = 0;
2523 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002524 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2525}
2526
Peter Boström0c4e06b2015-10-07 12:23:21 +02002527int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002528 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002529 const auto it = recv_streams_.find(ssrc);
2530 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002531 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002532 }
solenberg1ac56142015-10-13 03:58:19 -07002533 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534}
2535
Peter Boström0c4e06b2015-10-07 12:23:21 +02002536int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002537 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002538 const auto it = send_streams_.find(ssrc);
2539 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002540 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002541 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002542 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543}
2544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2546 if (playout) {
2547 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2548 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2549 LOG_RTCERR1(StartPlayout, channel);
2550 return false;
2551 }
2552 } else {
2553 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2554 engine()->voe()->base()->StopPlayout(channel);
2555 }
2556 return true;
2557}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558} // namespace cricket
2559
2560#endif // HAVE_WEBRTC_VOICE