blob: 016323892c841ca64310b8fdc8806caaecf83208 [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
11#ifdef HAVE_CONFIG_H
12#include <config.h>
13#endif
14
15#ifdef HAVE_WEBRTC_VOICE
16
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010017#include "webrtc/media/engine/webrtcvoiceengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
19#include <algorithm>
20#include <cstdio>
21#include <string>
22#include <vector>
23
kjellander@webrtc.org7ffeab52016-02-26 22:46:09 +010024#include "webrtc/audio_sink.h"
tfarina5237aaf2015-11-10 23:44:30 -080025#include "webrtc/base/arraysize.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000026#include "webrtc/base/base64.h"
27#include "webrtc/base/byteorder.h"
28#include "webrtc/base/common.h"
29#include "webrtc/base/helpers.h"
30#include "webrtc/base/logging.h"
31#include "webrtc/base/stringencode.h"
32#include "webrtc/base/stringutils.h"
Peter Boströmca8b4042016-03-08 14:24:13 -080033#include "webrtc/base/trace_event.h"
ivoc112a3d82015-10-16 02:22:18 -070034#include "webrtc/call/rtc_event_log.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000035#include "webrtc/common.h"
kjellandera96e2d72016-02-04 23:52:28 -080036#include "webrtc/media/base/audioframe.h"
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -080037#include "webrtc/media/base/audiosource.h"
kjellanderf4752772016-03-02 05:42:30 -080038#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080039#include "webrtc/media/base/streamparams.h"
kjellander@webrtc.org5ad12972016-02-12 06:39:40 +010040#include "webrtc/media/engine/webrtcmediaengine.h"
41#include "webrtc/media/engine/webrtcvoe.h"
solenberg26c8c912015-11-27 04:00:25 -080042#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080045#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070048namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049
solenbergbd138382015-11-20 16:08:07 -080050const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
51 webrtc::kTraceWarning | webrtc::kTraceError |
52 webrtc::kTraceCritical;
53const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
54 webrtc::kTraceInfo;
55
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056// On Windows Vista and newer, Microsoft introduced the concept of "Default
57// Communications Device". This means that there are two types of default
58// devices (old Wave Audio style default and Default Communications Device).
59//
60// On Windows systems which only support Wave Audio style default, uses either
61// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070063const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064#else
solenbergd97ec302015-10-07 01:40:33 -070065const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066#endif
67
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068// Parameter used for NACK.
69// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070070const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000071
72// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000073// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000074
75// Recommended bitrates:
76// 8-12 kb/s for NB speech,
77// 16-20 kb/s for WB speech,
78// 28-40 kb/s for FB speech,
79// 48-64 kb/s for FB mono music, and
80// 64-128 kb/s for FB stereo music.
81// The current implementation applies the following values to mono signals,
82// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070083const int kOpusBitrateNb = 12000;
84const int kOpusBitrateWb = 20000;
85const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000086
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000087// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -070088const int kOpusMinBitrate = 6000;
89const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +000090
wu@webrtc.orgde305012013-10-31 15:40:38 +000091// Default audio dscp value.
92// See http://tools.ietf.org/html/rfc2474 for details.
93// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -070094const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000095
Fredrik Solenbergb5727682015-12-04 15:22:19 +010096// Constants from voice_engine_defines.h.
97const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
98const int kMaxTelephoneEventCode = 255;
99const int kMinTelephoneEventDuration = 100;
100const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
101
solenberg31642aa2016-03-14 08:00:37 -0700102const int kMinPayloadType = 0;
103const int kMaxPayloadType = 127;
104
deadbeef884f5852016-01-15 09:20:04 -0800105class ProxySink : public webrtc::AudioSinkInterface {
106 public:
107 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
108
109 void OnData(const Data& audio) override { sink_->OnData(audio); }
110
111 private:
112 webrtc::AudioSinkInterface* sink_;
113};
114
solenberg0b675462015-10-09 01:37:09 -0700115bool ValidateStreamParams(const StreamParams& sp) {
116 if (sp.ssrcs.empty()) {
117 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
118 return false;
119 }
120 if (sp.ssrcs.size() > 1) {
121 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
122 return false;
123 }
124 return true;
125}
126
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700128std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129 std::stringstream ss;
130 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
131 << " (" << codec.id << ")";
132 return ss.str();
133}
Minyue Li7100dcd2015-03-27 05:05:59 +0100134
solenbergd97ec302015-10-07 01:40:33 -0700135std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136 std::stringstream ss;
137 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
138 << " (" << codec.pltype << ")";
139 return ss.str();
140}
141
solenbergd97ec302015-10-07 01:40:33 -0700142bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100143 return (_stricmp(codec.name.c_str(), ref_name) == 0);
144}
145
solenbergd97ec302015-10-07 01:40:33 -0700146bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100147 return (_stricmp(codec.plname, ref_name) == 0);
148}
149
solenbergd97ec302015-10-07 01:40:33 -0700150bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800151 const AudioCodec& codec,
152 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200153 for (const AudioCodec& c : codecs) {
154 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000155 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200156 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000157 }
158 return true;
159 }
160 }
161 return false;
162}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000163
solenberg0b675462015-10-09 01:37:09 -0700164bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
165 if (codecs.empty()) {
166 return true;
167 }
168 std::vector<int> payload_types;
169 for (const AudioCodec& codec : codecs) {
170 payload_types.push_back(codec.id);
171 }
172 std::sort(payload_types.begin(), payload_types.end());
173 auto it = std::unique(payload_types.begin(), payload_types.end());
174 return it == payload_types.end();
175}
176
Minyue Li7100dcd2015-03-27 05:05:59 +0100177// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800178bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100179 int value;
180 return codec.GetParam(feature, &value) && value == 1;
181}
182
183// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
184// otherwise. If the value (either from params or codec.bitrate) <=0, use the
185// default configuration. If the value is beyond feasible bit rate of Opus,
186// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700187int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100188 int bitrate = 0;
189 bool use_param = true;
190 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
191 bitrate = codec.bitrate;
192 use_param = false;
193 }
194 if (bitrate <= 0) {
195 if (max_playback_rate <= 8000) {
196 bitrate = kOpusBitrateNb;
197 } else if (max_playback_rate <= 16000) {
198 bitrate = kOpusBitrateWb;
199 } else {
200 bitrate = kOpusBitrateFb;
201 }
202
203 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
204 bitrate *= 2;
205 }
206 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
207 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
208 std::string rate_source =
209 use_param ? "Codec parameter \"maxaveragebitrate\"" :
210 "Supplied Opus bitrate";
211 LOG(LS_WARNING) << rate_source
212 << " is invalid and is replaced by: "
213 << bitrate;
214 }
215 return bitrate;
216}
217
218// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
219// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700220int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100221 int value;
222 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
223 return value;
224 }
225 return kOpusDefaultMaxPlaybackRate;
226}
227
solenbergd97ec302015-10-07 01:40:33 -0700228void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100229 bool* enable_codec_fec, int* max_playback_rate,
230 bool* enable_codec_dtx) {
231 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
232 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
233 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
234
235 // If OPUS, change what we send according to the "stereo" codec
236 // parameter, and not the "channels" parameter. We set
237 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
238 // the bitrate is not specified, i.e. is <= zero, we set it to the
239 // appropriate default value for mono or stereo Opus.
240
241 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
242 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
243}
244
solenberg566ef242015-11-06 15:34:49 -0800245webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
246 webrtc::AudioState::Config config;
247 config.voice_engine = voe_wrapper->engine();
248 return config;
249}
250
solenberg26c8c912015-11-27 04:00:25 -0800251class WebRtcVoiceCodecs final {
252 public:
253 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
254 // list and add a test which verifies VoE supports the listed codecs.
255 static std::vector<AudioCodec> SupportedCodecs() {
256 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
257 std::vector<AudioCodec> result;
258 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
259 // Change the sample rate of G722 to 8000 to match SDP.
260 MaybeFixupG722(&voe_codec, 8000);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000261 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100262 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000263 continue;
264 }
265
266 const CodecPref* pref = NULL;
tfarina5237aaf2015-11-10 23:44:30 -0800267 for (size_t j = 0; j < arraysize(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100268 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000269 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
270 kCodecPrefs[j].channels == voe_codec.channels) {
271 pref = &kCodecPrefs[j];
272 break;
273 }
274 }
275
276 if (pref) {
277 // Use the payload type that we've configured in our pref table;
278 // use the offset in our pref table to determine the sort order.
tfarina5237aaf2015-11-10 23:44:30 -0800279 AudioCodec codec(
280 pref->payload_type, voe_codec.plname, voe_codec.plfreq,
281 voe_codec.rate, voe_codec.channels,
282 static_cast<int>(arraysize(kCodecPrefs)) - (pref - kCodecPrefs));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000283 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100284 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000285 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000286 codec.bitrate = 0;
287 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100288 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000289 // Only add fmtp parameters that differ from the spec.
290 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
291 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000292 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000293 }
294 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
295 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000296 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000297 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000298 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800299 codec.AddFeedbackParam(
300 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000301
302 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000303 // when they can be set to values other than the default.
304 }
solenberg26c8c912015-11-27 04:00:25 -0800305 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000306 } else {
307 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
308 }
309 }
solenberg26c8c912015-11-27 04:00:25 -0800310 // Make sure they are in local preference order.
311 std::sort(result.begin(), result.end(), &AudioCodec::Preferable);
312 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000313 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000314
solenberg26c8c912015-11-27 04:00:25 -0800315 static bool ToCodecInst(const AudioCodec& in,
316 webrtc::CodecInst* out) {
317 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
318 // Change the sample rate of G722 to 8000 to match SDP.
319 MaybeFixupG722(&voe_codec, 8000);
320 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
321 voe_codec.rate, voe_codec.channels, 0);
322 bool multi_rate = IsCodecMultiRate(voe_codec);
323 // Allow arbitrary rates for ISAC to be specified.
324 if (multi_rate) {
325 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
326 codec.bitrate = 0;
327 }
328 if (codec.Matches(in)) {
329 if (out) {
330 // Fixup the payload type.
331 voe_codec.pltype = in.id;
332
333 // Set bitrate if specified.
334 if (multi_rate && in.bitrate != 0) {
335 voe_codec.rate = in.bitrate;
336 }
337
338 // Reset G722 sample rate to 16000 to match WebRTC.
339 MaybeFixupG722(&voe_codec, 16000);
340
341 // Apply codec-specific settings.
342 if (IsCodec(codec, kIsacCodecName)) {
343 // If ISAC and an explicit bitrate is not specified,
344 // enable auto bitrate adjustment.
345 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
346 }
347 *out = voe_codec;
348 }
349 return true;
350 }
351 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000352 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000353 }
solenberg26c8c912015-11-27 04:00:25 -0800354
355 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
356 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
357 if (IsCodec(codec, kCodecPrefs[i].name) &&
358 kCodecPrefs[i].clockrate == codec.plfreq) {
359 return kCodecPrefs[i].is_multi_rate;
360 }
361 }
362 return false;
363 }
364
365 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
366 // codec pacsize if it's valid, or we will pick the next smallest value we
367 // support.
368 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
369 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
370 for (const CodecPref& codec_pref : kCodecPrefs) {
371 if ((IsCodec(*codec, codec_pref.name) &&
372 codec_pref.clockrate == codec->plfreq) ||
373 IsCodec(*codec, kG722CodecName)) {
374 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
375 if (packet_size_ms) {
376 // Convert unit from milli-seconds to samples.
377 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
378 return true;
379 }
380 }
381 }
382 return false;
383 }
384
stefanba4c0e42016-02-04 04:12:24 -0800385 static const AudioCodec* GetPreferredCodec(
386 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800387 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800388 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800389 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800390 RTC_DCHECK(red_payload_type);
391 // Select the preferred send codec (the first non-telephone-event/CN codec).
392 for (const AudioCodec& codec : codecs) {
393 *red_payload_type = -1;
394 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
395 // Skip telephone-event/CN codec, which will be handled later.
396 continue;
397 }
398
399 // We'll use the first codec in the list to actually send audio data.
400 // Be sure to use the payload type requested by the remote side.
401 // "red", for RED audio, is a special case where the actual codec to be
402 // used is specified in params.
403 const AudioCodec* found_codec = &codec;
404 if (IsCodec(*found_codec, kRedCodecName)) {
405 // Parse out the RED parameters. If we fail, just ignore RED;
406 // we don't support all possible params/usage scenarios.
407 *red_payload_type = codec.id;
408 found_codec = GetRedSendCodec(*found_codec, codecs);
409 if (!found_codec) {
410 continue;
411 }
412 }
413 // Ignore codecs we don't know about. The negotiation step should prevent
414 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800415 webrtc::CodecInst voe_codec = {0};
416 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800417 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
418 continue;
419 }
solenberg72e29d22016-03-08 06:35:16 -0800420 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800421 return found_codec;
422 }
423 return nullptr;
424 }
425
solenberg26c8c912015-11-27 04:00:25 -0800426 private:
427 static const int kMaxNumPacketSize = 6;
428 struct CodecPref {
429 const char* name;
430 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800431 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800432 int payload_type;
433 bool is_multi_rate;
434 int packet_sizes_ms[kMaxNumPacketSize];
435 };
436 // Note: keep the supported packet sizes in ascending order.
437 static const CodecPref kCodecPrefs[12];
438
439 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
440 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
441 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
442 if (packet_size_ms && packet_size_ms <= ptime_ms) {
443 selected_packet_size_ms = packet_size_ms;
444 }
445 }
446 return selected_packet_size_ms;
447 }
448
449 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
450 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
451 // codec.
452 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
453 if (IsCodec(*voe_codec, kG722CodecName)) {
454 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
455 // has changed, and this special case is no longer needed.
456 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
457 voe_codec->plfreq = new_plfreq;
458 }
459 }
stefanba4c0e42016-02-04 04:12:24 -0800460
461 static const AudioCodec* GetRedSendCodec(
462 const AudioCodec& red_codec,
463 const std::vector<AudioCodec>& all_codecs) {
464 // Get the RED encodings from the parameter with no name. This may
465 // change based on what is discussed on the Jingle list.
466 // The encoding parameter is of the form "a/b"; we only support where
467 // a == b. Verify this and parse out the value into red_pt.
468 // If the parameter value is absent (as it will be until we wire up the
469 // signaling of this message), use the second codec specified (i.e. the
470 // one after "red") as the encoding parameter.
471 int red_pt = -1;
472 std::string red_params;
473 CodecParameterMap::const_iterator it = red_codec.params.find("");
474 if (it != red_codec.params.end()) {
475 red_params = it->second;
476 std::vector<std::string> red_pts;
477 if (rtc::split(red_params, '/', &red_pts) != 2 ||
478 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
479 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
480 return nullptr;
481 }
482 } else if (red_codec.params.empty()) {
483 LOG(LS_WARNING) << "RED params not present, using defaults";
484 if (all_codecs.size() > 1) {
485 red_pt = all_codecs[1].id;
486 }
487 }
488
489 // Try to find red_pt in |codecs|.
490 for (const AudioCodec& codec : all_codecs) {
491 if (codec.id == red_pt) {
492 return &codec;
493 }
494 }
495 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
496 return nullptr;
497 }
solenberg26c8c912015-11-27 04:00:25 -0800498};
499
500const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
501 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
502 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
503 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
504 // G722 should be advertised as 8000 Hz because of the RFC "bug".
505 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
506 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
507 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
508 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
509 { kCnCodecName, 32000, 1, 106, false, { } },
510 { kCnCodecName, 16000, 1, 105, false, { } },
511 { kCnCodecName, 8000, 1, 13, false, { } },
512 { kRedCodecName, 8000, 1, 127, false, { } },
513 { kDtmfCodecName, 8000, 1, 126, false, { } },
514};
515} // namespace {
516
517bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
518 webrtc::CodecInst* out) {
519 return WebRtcVoiceCodecs::ToCodecInst(in, out);
520}
521
522WebRtcVoiceEngine::WebRtcVoiceEngine()
523 : voe_wrapper_(new VoEWrapper()),
524 audio_state_(webrtc::AudioState::Create(MakeAudioStateConfig(voe()))) {
525 Construct();
526}
527
528WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper)
529 : voe_wrapper_(voe_wrapper) {
530 Construct();
531}
532
533void WebRtcVoiceEngine::Construct() {
534 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
535 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
536
537 signal_thread_checker_.DetachFromThread();
538 std::memset(&default_agc_config_, 0, sizeof(default_agc_config_));
solenberg246b8172015-12-08 09:50:23 -0800539 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
solenberg26c8c912015-11-27 04:00:25 -0800540
541 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
542 webrtc::Trace::SetTraceCallback(this);
543
544 // Load our audio codec list.
545 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000546}
547
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000548WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800549 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000550 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000551 if (adm_) {
552 voe_wrapper_.reset();
553 adm_->Release();
554 adm_ = NULL;
555 }
solenbergbd138382015-11-20 16:08:07 -0800556 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000557}
558
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000559bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
solenberg566ef242015-11-06 15:34:49 -0800560 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700561 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000562 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
563 bool res = InitInternal();
564 if (res) {
565 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
566 } else {
567 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
568 Terminate();
569 }
570 return res;
571}
572
573bool WebRtcVoiceEngine::InitInternal() {
solenberg566ef242015-11-06 15:34:49 -0800574 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg72e29d22016-03-08 06:35:16 -0800575 // Temporarily turn logging level up for the Init call.
solenbergbd138382015-11-20 16:08:07 -0800576 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800577 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000578 if (voe_wrapper_->base()->Init(adm_) == -1) {
579 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000580 return false;
581 }
solenbergbd138382015-11-20 16:08:07 -0800582 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000583
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000584 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800585 // calling ApplyOptions or the default will be overwritten.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000586 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
587 LOG_RTCERR0(GetAgcConfig);
588 return false;
589 }
590
solenberg0f7d2932016-01-15 01:40:39 -0800591 // Set default engine options.
592 {
593 AudioOptions options;
594 options.echo_cancellation = rtc::Optional<bool>(true);
595 options.auto_gain_control = rtc::Optional<bool>(true);
596 options.noise_suppression = rtc::Optional<bool>(true);
597 options.highpass_filter = rtc::Optional<bool>(true);
598 options.stereo_swapping = rtc::Optional<bool>(false);
599 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
600 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
601 options.typing_detection = rtc::Optional<bool>(true);
602 options.adjust_agc_delta = rtc::Optional<int>(0);
603 options.experimental_agc = rtc::Optional<bool>(false);
604 options.extended_filter_aec = rtc::Optional<bool>(false);
605 options.delay_agnostic_aec = rtc::Optional<bool>(false);
606 options.experimental_ns = rtc::Optional<bool>(false);
solenberg0f7d2932016-01-15 01:40:39 -0800607 if (!ApplyOptions(options)) {
608 return false;
609 }
610 }
611
solenberg72e29d22016-03-08 06:35:16 -0800612 // Print our codec list again for the call diagnostic log.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000613 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200614 for (const AudioCodec& codec : codecs_) {
615 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000616 }
617
solenberg246b8172015-12-08 09:50:23 -0800618 SetDefaultDevices();
619
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000620 initialized_ = true;
621 return true;
622}
623
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000624void WebRtcVoiceEngine::Terminate() {
solenberg566ef242015-11-06 15:34:49 -0800625 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000626 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
627 initialized_ = false;
628
629 StopAecDump();
630
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000631 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000632}
633
solenberg566ef242015-11-06 15:34:49 -0800634rtc::scoped_refptr<webrtc::AudioState>
635 WebRtcVoiceEngine::GetAudioState() const {
636 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
637 return audio_state_;
638}
639
nisse51542be2016-02-12 02:27:06 -0800640VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
641 webrtc::Call* call,
642 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200643 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800644 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800645 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000646}
647
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000648bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800649 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikac14f5ff2015-09-23 14:08:33 +0200650 LOG(LS_INFO) << "ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800651 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800652
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000653 // kEcConference is AEC with high suppression.
654 webrtc::EcModes ec_mode = webrtc::kEcConference;
655 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
656 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
657 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700658 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000659 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700660 << *options.aecm_generate_comfort_noise
661 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000662 }
663
kjellanderfcfc8042016-01-14 11:01:09 -0800664#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000665 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100666 options.echo_cancellation = rtc::Optional<bool>(false);
667 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200668 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000669#elif defined(ANDROID)
670 ec_mode = webrtc::kEcAecm;
671#endif
672
kjellanderfcfc8042016-01-14 11:01:09 -0800673#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000674 // Set the AGC mode for iOS as well despite disabling it above, to avoid
675 // unsupported configuration errors from webrtc.
676 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100677 options.typing_detection = rtc::Optional<bool>(false);
678 options.experimental_agc = rtc::Optional<bool>(false);
679 options.extended_filter_aec = rtc::Optional<bool>(false);
680 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000681#endif
682
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100683 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
684 // where the feature is not supported.
685 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800686#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700687 if (options.delay_agnostic_aec) {
688 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100689 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100690 options.echo_cancellation = rtc::Optional<bool>(true);
691 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100692 ec_mode = webrtc::kEcConference;
693 }
694 }
695#endif
696
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000697 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
698
kwiberg102c6a62015-10-30 02:47:38 -0700699 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000700 // Check if platform supports built-in EC. Currently only supported on
701 // Android and in combination with Java based audio layer.
702 // TODO(henrika): investigate possibility to support built-in EC also
703 // in combination with Open SL ES audio.
704 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200705 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200706 // Built-in EC exists on this device and use_delay_agnostic_aec is not
707 // overriding it. Enable/Disable it according to the echo_cancellation
708 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200709 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700710 *options.echo_cancellation && !use_delay_agnostic_aec;
Bjorn Volcker73f72102015-06-03 14:50:15 +0200711 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
712 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100713 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000714 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100715 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000716 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
717 }
718 }
kwiberg102c6a62015-10-30 02:47:38 -0700719 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
720 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000721 return false;
722 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700723 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200724 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000725 }
726#if !defined(ANDROID)
727 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700728 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
729 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000730 return false;
731 }
732#endif
733 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700734 bool cn = options.aecm_generate_comfort_noise.value_or(false);
735 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
736 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000737 return false;
738 }
739 }
740 }
741
kwiberg102c6a62015-10-30 02:47:38 -0700742 if (options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200743 const bool built_in_agc = voe_wrapper_->hw()->BuiltInAGCIsAvailable();
744 if (built_in_agc) {
kwiberg102c6a62015-10-30 02:47:38 -0700745 if (voe_wrapper_->hw()->EnableBuiltInAGC(*options.auto_gain_control) ==
746 0 &&
747 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200748 // Disable internal software AGC if built-in AGC is enabled,
749 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100750 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200751 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
752 }
753 }
kwiberg102c6a62015-10-30 02:47:38 -0700754 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
755 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000756 return false;
757 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700758 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
759 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000760 }
761 }
762
kwiberg102c6a62015-10-30 02:47:38 -0700763 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
764 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000765 // Override default_agc_config_. Generally, an unset option means "leave
766 // the VoE bits alone" in this function, so we want whatever is set to be
767 // stored as the new "default". If we didn't, then setting e.g.
768 // tx_agc_target_dbov would reset digital compression gain and limiter
769 // settings.
770 // Also, if we don't update default_agc_config_, then adjust_agc_delta
771 // would be an offset from the original values, and not whatever was set
772 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700773 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
774 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000775 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700776 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000777 default_agc_config_.digitalCompressionGaindB);
778 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700779 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000780 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
781 LOG_RTCERR3(SetAgcConfig,
782 default_agc_config_.targetLeveldBOv,
783 default_agc_config_.digitalCompressionGaindB,
784 default_agc_config_.limiterEnable);
785 return false;
786 }
787 }
788
kwiberg102c6a62015-10-30 02:47:38 -0700789 if (options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200790 const bool built_in_ns = voe_wrapper_->hw()->BuiltInNSIsAvailable();
791 if (built_in_ns) {
kwiberg102c6a62015-10-30 02:47:38 -0700792 if (voe_wrapper_->hw()->EnableBuiltInNS(*options.noise_suppression) ==
793 0 &&
794 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200795 // Disable internal software NS if built-in NS is enabled,
796 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100797 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200798 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
799 }
800 }
kwiberg102c6a62015-10-30 02:47:38 -0700801 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
802 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000803 return false;
804 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700805 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200806 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000807 }
808 }
809
kwiberg102c6a62015-10-30 02:47:38 -0700810 if (options.highpass_filter) {
811 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
812 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
813 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000814 return false;
815 }
816 }
817
kwiberg102c6a62015-10-30 02:47:38 -0700818 if (options.stereo_swapping) {
819 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
820 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
821 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
822 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000823 return false;
824 }
825 }
826
kwiberg102c6a62015-10-30 02:47:38 -0700827 if (options.audio_jitter_buffer_max_packets) {
828 LOG(LS_INFO) << "NetEq capacity is "
829 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200830 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700831 new webrtc::NetEqCapacityConfig(
832 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200833 }
834
kwiberg102c6a62015-10-30 02:47:38 -0700835 if (options.audio_jitter_buffer_fast_accelerate) {
836 LOG(LS_INFO) << "NetEq fast mode? "
837 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200838 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700839 new webrtc::NetEqFastAccelerate(
840 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200841 }
842
kwiberg102c6a62015-10-30 02:47:38 -0700843 if (options.typing_detection) {
844 LOG(LS_INFO) << "Typing detection is enabled? "
845 << *options.typing_detection;
846 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000847 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700848 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000849 }
850 }
851
kwiberg102c6a62015-10-30 02:47:38 -0700852 if (options.adjust_agc_delta) {
853 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
854 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000855 return false;
856 }
857 }
858
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000859 webrtc::Config config;
860
kwiberg102c6a62015-10-30 02:47:38 -0700861 if (options.delay_agnostic_aec)
862 delay_agnostic_aec_ = options.delay_agnostic_aec;
863 if (delay_agnostic_aec_) {
864 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700865 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700866 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100867 }
868
kwiberg102c6a62015-10-30 02:47:38 -0700869 if (options.extended_filter_aec) {
870 extended_filter_aec_ = options.extended_filter_aec;
871 }
872 if (extended_filter_aec_) {
873 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200874 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700875 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000876 }
877
kwiberg102c6a62015-10-30 02:47:38 -0700878 if (options.experimental_ns) {
879 experimental_ns_ = options.experimental_ns;
880 }
881 if (experimental_ns_) {
882 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000883 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700884 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000885 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000886
887 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
888 // returns NULL on audio_processing().
889 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
890 if (audioproc) {
891 audioproc->SetExtraOptions(config);
892 }
893
kwiberg102c6a62015-10-30 02:47:38 -0700894 if (options.recording_sample_rate) {
895 LOG(LS_INFO) << "Recording sample rate is "
896 << *options.recording_sample_rate;
897 if (voe_wrapper_->hw()->SetRecordingSampleRate(
898 *options.recording_sample_rate)) {
899 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000900 }
901 }
902
kwiberg102c6a62015-10-30 02:47:38 -0700903 if (options.playout_sample_rate) {
904 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
905 if (voe_wrapper_->hw()->SetPlayoutSampleRate(
906 *options.playout_sample_rate)) {
907 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000908 }
909 }
910
911 return true;
912}
913
solenberg246b8172015-12-08 09:50:23 -0800914void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800915 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800916#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800917 int in_id = kDefaultAudioDeviceId;
918 int out_id = kDefaultAudioDeviceId;
919 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
920 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921
solenbergc1a1b352015-09-22 13:31:20 -0700922 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800923 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
924 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000925 ret = false;
926 }
solenberg246b8172015-12-08 09:50:23 -0800927 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
928 if (ap) {
929 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 }
931
solenberg246b8172015-12-08 09:50:23 -0800932 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
933 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934 ret = false;
935 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800938 LOG(LS_INFO) << "Set microphone to (id=" << in_id
939 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940 }
kjellanderfcfc8042016-01-14 11:01:09 -0800941#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942}
943
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800945 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946 unsigned int ulevel;
947 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
948 LOG_RTCERR1(GetSpeakerVolume, level);
949 return false;
950 }
951 *level = ulevel;
952 return true;
953}
954
955bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800956 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700957 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
959 LOG_RTCERR1(SetSpeakerVolume, level);
960 return false;
961 }
962 return true;
963}
964
965int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800966 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 unsigned int ulevel;
968 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
969 static_cast<int>(ulevel) : -1;
970}
971
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800973 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 return codecs_;
975}
976
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100977RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800978 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100979 RtpCapabilities capabilities;
980 capabilities.header_extensions.push_back(RtpHeaderExtension(
981 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
982 capabilities.header_extensions.push_back(
983 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
984 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800985 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
986 "Enabled") {
987 capabilities.header_extensions.push_back(RtpHeaderExtension(
988 kRtpTransportSequenceNumberHeaderExtension,
989 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
990 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100991 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992}
993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800995 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996 return voe_wrapper_->error();
997}
998
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1000 int length) {
solenberg566ef242015-11-06 15:34:49 -08001001 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001002 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001004 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001006 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001008 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001010 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011
solenberg72e29d22016-03-08 06:35:16 -08001012 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 if (length < 72) {
1014 std::string msg(trace, length);
1015 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1016 LOG_V(sev) << msg;
1017 } else {
1018 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +02001019 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 }
1021}
1022
solenberg63b34542015-09-29 06:06:31 -07001023void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001024 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1025 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 channels_.push_back(channel);
1027}
1028
solenberg63b34542015-09-29 06:06:31 -07001029void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001030 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -07001031 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -08001032 RTC_DCHECK(it != channels_.end());
1033 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034}
1035
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036// Adjusts the default AGC target level by the specified delta.
1037// NB: If we start messing with other config fields, we'll want
1038// to save the current webrtc::AgcConfig as well.
1039bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -08001040 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 webrtc::AgcConfig config = default_agc_config_;
1042 config.targetLeveldBOv -= delta;
1043
1044 LOG(LS_INFO) << "Adjusting AGC level from default -"
1045 << default_agc_config_.targetLeveldBOv << "dB to -"
1046 << config.targetLeveldBOv << "dB";
1047
1048 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1049 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1050 return false;
1051 }
1052 return true;
1053}
1054
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001055bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
solenberg566ef242015-11-06 15:34:49 -08001056 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057 if (initialized_) {
1058 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1059 return false;
1060 }
1061 if (adm_) {
1062 adm_->Release();
1063 adm_ = NULL;
1064 }
1065 if (adm) {
1066 adm_ = adm;
1067 adm_->AddRef();
1068 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001069 return true;
1070}
1071
ivocd66b44d2016-01-15 03:06:36 -08001072bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
1073 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -08001074 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001075 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001076 if (!aec_dump_file_stream) {
1077 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001078 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001079 LOG(LS_WARNING) << "Could not close file.";
1080 return false;
1081 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001082 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001083 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1084 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001085 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001086 LOG_RTCERR0(StartDebugRecording);
1087 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001088 return false;
1089 }
1090 is_dumping_aec_ = true;
1091 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001092}
1093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001095 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 if (!is_dumping_aec_) {
1097 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001098 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1099 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001100 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 } else {
1102 is_dumping_aec_ = true;
1103 }
1104 }
1105}
1106
1107void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001108 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 if (is_dumping_aec_) {
1110 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001111 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 webrtc::AudioProcessing::kNoError) {
1113 LOG_RTCERR0(StopDebugRecording);
1114 }
1115 is_dumping_aec_ = false;
1116 }
1117}
1118
ivoc112a3d82015-10-16 02:22:18 -07001119bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001120 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001121 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1122 if (event_log) {
1123 return event_log->StartLogging(file);
1124 }
1125 LOG_RTCERR0(StartRtcEventLog);
1126 return false;
ivoc112a3d82015-10-16 02:22:18 -07001127}
1128
1129void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001130 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001131 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1132 if (event_log) {
1133 event_log->StopLogging();
1134 return;
1135 }
1136 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001137}
1138
solenberg0a617e22015-10-20 15:49:38 -07001139int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001140 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001141 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001142}
1143
solenbergc96df772015-10-21 13:01:53 -07001144class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001145 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001146 public:
solenbergc96df772015-10-21 13:01:53 -07001147 WebRtcAudioSendStream(int ch, webrtc::AudioTransport* voe_audio_transport,
solenberg3a941542015-11-16 07:34:50 -08001148 uint32_t ssrc, const std::string& c_name,
1149 const std::vector<webrtc::RtpExtension>& extensions,
1150 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001151 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001152 call_(call),
1153 config_(nullptr) {
solenberg85a04962015-10-27 03:35:21 -07001154 RTC_DCHECK_GE(ch, 0);
1155 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1156 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001157 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001158 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001159 config_.rtp.ssrc = ssrc;
1160 config_.rtp.c_name = c_name;
1161 config_.voe_channel_id = ch;
1162 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001163 }
solenberg3a941542015-11-16 07:34:50 -08001164
solenbergc96df772015-10-21 13:01:53 -07001165 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001166 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001167 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001168 call_->DestroyAudioSendStream(stream_);
1169 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001170
solenberg3a941542015-11-16 07:34:50 -08001171 void RecreateAudioSendStream(
1172 const std::vector<webrtc::RtpExtension>& extensions) {
1173 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1174 if (stream_) {
1175 call_->DestroyAudioSendStream(stream_);
1176 stream_ = nullptr;
1177 }
1178 config_.rtp.extensions = extensions;
1179 RTC_DCHECK(!stream_);
1180 stream_ = call_->CreateAudioSendStream(config_);
1181 RTC_CHECK(stream_);
1182 }
1183
solenberg8842c3e2016-03-11 03:06:41 -08001184 bool SendTelephoneEvent(int payload_type, int event, int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001185 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1186 RTC_DCHECK(stream_);
1187 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1188 }
1189
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001190 void SetSend(bool send) {
1191 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1192 send_ = send;
1193 UpdateSendState();
1194 }
1195
solenberg3a941542015-11-16 07:34:50 -08001196 webrtc::AudioSendStream::Stats GetStats() const {
1197 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1198 RTC_DCHECK(stream_);
1199 return stream_->GetStats();
1200 }
1201
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001202 // Starts the sending by setting ourselves as a sink to the AudioSource to
1203 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001204 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001205 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001206 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001207 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001208 RTC_DCHECK(source);
1209 if (source_) {
1210 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001211 return;
1212 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001213 source->SetSink(this);
1214 source_ = source;
1215 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001216 }
1217
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001218 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001219 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001220 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001221 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001222 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001223 if (source_) {
1224 source_->SetSink(nullptr);
1225 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001226 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001227 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001228 }
1229
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001230 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001231 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001232 void OnData(const void* audio_data,
1233 int bits_per_sample,
1234 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001235 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001236 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001237 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001238 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001239 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001240 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001241 audio_data,
1242 bits_per_sample,
1243 sample_rate,
1244 number_of_channels,
1245 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001246 }
1247
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001248 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001249 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001250 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001251 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001252 // Set |source_| to nullptr to make sure no more callback will get into
1253 // the source.
1254 source_ = nullptr;
1255 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001256 }
1257
1258 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001259 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001260 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001261 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001262 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001263
1264 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001265 void UpdateSendState() {
1266 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1267 RTC_DCHECK(stream_);
1268 if (send_ && source_ != nullptr) {
1269 stream_->Start();
1270 } else { // !send || source_ = nullptr
1271 stream_->Stop();
1272 }
1273 }
1274
solenberg566ef242015-11-06 15:34:49 -08001275 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001276 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001277 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1278 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001279 webrtc::AudioSendStream::Config config_;
1280 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1281 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001282 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001283
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001284 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001285 // PeerConnection will make sure invalidating the pointer before the object
1286 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001287 AudioSource* source_ = nullptr;
1288 bool send_ = false;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001289
solenbergc96df772015-10-21 13:01:53 -07001290 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1291};
1292
1293class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1294 public:
stefanba4c0e42016-02-04 04:12:24 -08001295 WebRtcAudioReceiveStream(int ch,
1296 uint32_t remote_ssrc,
1297 uint32_t local_ssrc,
1298 bool use_transport_cc,
1299 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001300 const std::vector<webrtc::RtpExtension>& extensions,
1301 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001302 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001303 RTC_DCHECK_GE(ch, 0);
1304 RTC_DCHECK(call);
1305 config_.rtp.remote_ssrc = remote_ssrc;
1306 config_.rtp.local_ssrc = local_ssrc;
1307 config_.voe_channel_id = ch;
1308 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001309 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001310 }
solenbergc96df772015-10-21 13:01:53 -07001311
solenberg7add0582015-11-20 09:59:34 -08001312 ~WebRtcAudioReceiveStream() {
1313 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1314 call_->DestroyAudioReceiveStream(stream_);
1315 }
1316
1317 void RecreateAudioReceiveStream(
1318 const std::vector<webrtc::RtpExtension>& extensions) {
1319 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001320 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001321 }
stefanba4c0e42016-02-04 04:12:24 -08001322 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001323 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001324 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001325 }
1326
1327 webrtc::AudioReceiveStream::Stats GetStats() const {
1328 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1329 RTC_DCHECK(stream_);
1330 return stream_->GetStats();
1331 }
1332
1333 int channel() const {
1334 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1335 return config_.voe_channel_id;
1336 }
solenbergc96df772015-10-21 13:01:53 -07001337
kwiberg686a8ef2016-02-26 03:00:35 -08001338 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001339 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001340 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001341 }
1342
solenbergc96df772015-10-21 13:01:53 -07001343 private:
stefanba4c0e42016-02-04 04:12:24 -08001344 void RecreateAudioReceiveStream(
1345 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001346 const std::vector<webrtc::RtpExtension>& extensions) {
1347 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1348 if (stream_) {
1349 call_->DestroyAudioReceiveStream(stream_);
1350 stream_ = nullptr;
1351 }
1352 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001353 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001354 RTC_DCHECK(!stream_);
1355 stream_ = call_->CreateAudioReceiveStream(config_);
1356 RTC_CHECK(stream_);
1357 }
1358
1359 rtc::ThreadChecker worker_thread_checker_;
1360 webrtc::Call* call_ = nullptr;
1361 webrtc::AudioReceiveStream::Config config_;
1362 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1363 // configuration changes.
1364 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001365
1366 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001367};
1368
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001369WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001370 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001371 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001372 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001373 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001374 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001375 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001376 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001377 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378}
1379
1380WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001381 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001382 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001383 // TODO(solenberg): Should be able to delete the streams directly, without
1384 // going through RemoveNnStream(), once stream objects handle
1385 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001386 while (!send_streams_.empty()) {
1387 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001388 }
solenberg7add0582015-11-20 09:59:34 -08001389 while (!recv_streams_.empty()) {
1390 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 }
solenberg0a617e22015-10-20 15:49:38 -07001392 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393}
1394
nisse51542be2016-02-12 02:27:06 -08001395rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1396 return kAudioDscpValue;
1397}
1398
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001399bool WebRtcVoiceMediaChannel::SetSendParameters(
1400 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001401 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001402 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001403 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1404 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001405 // TODO(pthatcher): Refactor this to be more clean now that we have
1406 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001407
1408 if (!SetSendCodecs(params.codecs)) {
1409 return false;
1410 }
1411
solenberg7e4e01a2015-12-02 08:05:01 -08001412 if (!ValidateRtpExtensions(params.extensions)) {
1413 return false;
1414 }
1415 std::vector<webrtc::RtpExtension> filtered_extensions =
1416 FilterRtpExtensions(params.extensions,
1417 webrtc::RtpExtension::IsSupportedForAudio, true);
1418 if (send_rtp_extensions_ != filtered_extensions) {
1419 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001420 for (auto& it : send_streams_) {
1421 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1422 }
1423 }
1424
1425 if (!SetMaxSendBandwidth(params.max_bandwidth_bps)) {
1426 return false;
1427 }
1428 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001429}
1430
1431bool WebRtcVoiceMediaChannel::SetRecvParameters(
1432 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001433 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001434 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001435 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1436 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001437 // TODO(pthatcher): Refactor this to be more clean now that we have
1438 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001439
1440 if (!SetRecvCodecs(params.codecs)) {
1441 return false;
1442 }
1443
solenberg7e4e01a2015-12-02 08:05:01 -08001444 if (!ValidateRtpExtensions(params.extensions)) {
1445 return false;
1446 }
1447 std::vector<webrtc::RtpExtension> filtered_extensions =
1448 FilterRtpExtensions(params.extensions,
1449 webrtc::RtpExtension::IsSupportedForAudio, false);
1450 if (recv_rtp_extensions_ != filtered_extensions) {
1451 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001452 for (auto& it : recv_streams_) {
1453 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1454 }
1455 }
solenberg7add0582015-11-20 09:59:34 -08001456 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001457}
1458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001460 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 LOG(LS_INFO) << "Setting voice channel options: "
1462 << options.ToString();
1463
1464 // We retain all of the existing options, and apply the given ones
1465 // on top. This means there is no way to "clear" options such that
1466 // they go back to the engine default.
1467 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001468 if (!engine()->ApplyOptions(options_)) {
1469 LOG(LS_WARNING) <<
1470 "Failed to apply engine options during channel SetOptions.";
1471 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 LOG(LS_INFO) << "Set voice channel options. Current options: "
1474 << options_.ToString();
1475 return true;
1476}
1477
1478bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1479 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001480 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001481
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001483 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001484
1485 if (!VerifyUniquePayloadTypes(codecs)) {
1486 LOG(LS_ERROR) << "Codec payload types overlap.";
1487 return false;
1488 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489
1490 std::vector<AudioCodec> new_codecs;
1491 // Find all new codecs. We allow adding new codecs but don't allow changing
1492 // the payload type of codecs that is already configured since we might
1493 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001494 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001496 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1497 if (old_codec.id != codec.id) {
1498 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 return false;
1500 }
1501 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001502 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503 }
1504 }
1505 if (new_codecs.empty()) {
1506 // There are no new codecs to configure. Already configured codecs are
1507 // never removed.
1508 return true;
1509 }
1510
1511 if (playout_) {
1512 // Receive codecs can not be changed while playing. So we temporarily
1513 // pause playout.
1514 PausePlayout();
1515 }
1516
solenberg26c8c912015-11-27 04:00:25 -08001517 bool result = true;
1518 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001519 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001520 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1521 LOG(LS_INFO) << ToString(codec);
1522 voe_codec.pltype = codec.id;
1523 for (const auto& ch : recv_streams_) {
1524 if (engine()->voe()->codec()->SetRecPayloadType(
1525 ch.second->channel(), voe_codec) == -1) {
1526 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1527 ToString(voe_codec));
1528 result = false;
1529 }
1530 }
1531 } else {
1532 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1533 result = false;
1534 break;
1535 }
1536 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001537 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538 recv_codecs_ = codecs;
1539 }
1540
1541 if (desired_playout_ && !playout_) {
1542 ResumePlayout();
1543 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001544 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545}
1546
solenberg72e29d22016-03-08 06:35:16 -08001547// Utility function called from SetSendParameters() to extract current send
1548// codec settings from the given list of codecs (originally from SDP). Both send
1549// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001550bool WebRtcVoiceMediaChannel::SetSendCodecs(
1551 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001552 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001553 // TODO(solenberg): Validate input - that payload types don't overlap, are
1554 // within range, filter out codecs we don't support,
solenberg31642aa2016-03-14 08:00:37 -07001555 // redundant codecs etc - the same way it is done for
1556 // RtpHeaderExtensions.
solenbergd97ec302015-10-07 01:40:33 -07001557
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001558 // Find the DTMF telephone event "codec" payload type.
1559 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001560 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001561 if (IsCodec(codec, kDtmfCodecName)) {
solenberg31642aa2016-03-14 08:00:37 -07001562 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1563 return false;
1564 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001565 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1566 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001567 }
1568 }
1569
solenberg72e29d22016-03-08 06:35:16 -08001570 // Scan through the list to figure out the codec to use for sending, along
1571 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1572 // parameters.
1573 {
1574 SendCodecSpec send_codec_spec;
1575 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1576
1577 // Find send codec (the first non-telephone-event/CN codec).
1578 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1579 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1580 if (!codec) {
1581 LOG(LS_WARNING) << "Received empty list of codecs.";
1582 return false;
1583 }
1584
1585 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1586
1587 // This condition is apparently here because Opus does not support RED and
1588 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1589 // such limitations.
1590 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1591 if (send_codec_spec.red_payload_type == -1) {
1592 send_codec_spec.nack_enabled = HasNack(*codec);
1593 // For Opus as the send codec, we are to determine inband FEC, maximum
1594 // playback rate, and opus internal dtx.
1595 if (IsCodec(*codec, kOpusCodecName)) {
1596 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1597 &send_codec_spec.enable_codec_fec,
1598 &send_codec_spec.opus_max_playback_rate,
1599 &send_codec_spec.enable_opus_dtx);
1600 }
1601
1602 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1603 int ptime_ms = 0;
1604 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1605 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1606 &send_codec_spec.codec_inst, ptime_ms)) {
1607 LOG(LS_WARNING) << "Failed to set packet size for codec "
1608 << send_codec_spec.codec_inst.plname;
1609 return false;
1610 }
1611 }
1612 }
1613
1614 // Loop through the codecs list again to find the CN codec.
1615 // TODO(solenberg): Break out into a separate function?
1616 for (const AudioCodec& codec : codecs) {
1617 // Ignore codecs we don't know about. The negotiation step should prevent
1618 // this, but double-check to be sure.
1619 webrtc::CodecInst voe_codec = {0};
1620 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1621 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1622 continue;
1623 }
1624
1625 if (IsCodec(codec, kCnCodecName)) {
1626 // Turn voice activity detection/comfort noise on if supported.
1627 // Set the wideband CN payload type appropriately.
1628 // (narrowband always uses the static payload type 13).
1629 int cng_plfreq = -1;
1630 switch (codec.clockrate) {
1631 case 8000:
1632 case 16000:
1633 case 32000:
1634 cng_plfreq = codec.clockrate;
1635 break;
1636 default:
1637 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1638 << " not supported.";
1639 continue;
1640 }
1641 send_codec_spec.cng_payload_type = codec.id;
1642 send_codec_spec.cng_plfreq = cng_plfreq;
1643 break;
1644 }
1645 }
1646
1647 // Latch in the new state.
1648 send_codec_spec_ = std::move(send_codec_spec);
1649 }
1650
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001651 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001652 for (const auto& ch : send_streams_) {
solenberg72e29d22016-03-08 06:35:16 -08001653 if (!SetSendCodecs(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001654 return false;
1655 }
1656 }
1657
solenberg72e29d22016-03-08 06:35:16 -08001658 // Set nack status on receive channels.
1659 if (!send_streams_.empty()) {
1660 for (const auto& kv : recv_streams_) {
1661 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1662 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001663 }
solenberg0a617e22015-10-20 15:49:38 -07001664
stefanba4c0e42016-02-04 04:12:24 -08001665 // Check if the transport cc feedback has changed on the preferred send codec,
1666 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001667 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1668 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1669 "codec has changed.";
1670 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1671 for (auto& kv : recv_streams_) {
1672 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1673 }
1674 }
1675
1676 return true;
1677}
1678
1679// Apply current codec settings to a single voe::Channel used for sending.
1680bool WebRtcVoiceMediaChannel::SetSendCodecs(int channel) {
1681 // Disable VAD, FEC, and RED unless we know the other side wants them.
1682 engine()->voe()->codec()->SetVADStatus(channel, false);
1683 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1684 engine()->voe()->rtp()->SetREDStatus(channel, false);
1685 engine()->voe()->codec()->SetFECStatus(channel, false);
1686
1687 if (send_codec_spec_.red_payload_type != -1) {
1688 // Enable redundant encoding of the specified codec. Treat any
1689 // failure as a fatal internal error.
1690 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1691 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1692 send_codec_spec_.red_payload_type) == -1) {
1693 LOG_RTCERR3(SetREDStatus, channel, true,
1694 send_codec_spec_.red_payload_type);
1695 return false;
1696 }
1697 }
1698
1699 SetNack(channel, send_codec_spec_.nack_enabled);
1700
1701 // Set the codec immediately, since SetVADStatus() depends on whether
1702 // the current codec is mono or stereo.
1703 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1704 return false;
1705 }
1706
1707 // FEC should be enabled after SetSendCodec.
1708 if (send_codec_spec_.enable_codec_fec) {
1709 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1710 << channel;
1711 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1712 // Enable codec internal FEC. Treat any failure as fatal internal error.
1713 LOG_RTCERR2(SetFECStatus, channel, true);
1714 return false;
1715 }
1716 }
1717
1718 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1719 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1720 // send codec has to be Opus.
1721
1722 // Set Opus internal DTX.
1723 LOG(LS_INFO) << "Attempt to "
1724 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1725 << " Opus DTX on channel "
1726 << channel;
1727 if (engine()->voe()->codec()->SetOpusDtx(channel,
1728 send_codec_spec_.enable_opus_dtx)) {
1729 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1730 return false;
1731 }
1732
1733 // If opus_max_playback_rate <= 0, the default maximum playback rate
1734 // (48 kHz) will be used.
1735 if (send_codec_spec_.opus_max_playback_rate > 0) {
1736 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1737 << send_codec_spec_.opus_max_playback_rate
1738 << " Hz on channel "
1739 << channel;
1740 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1741 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1742 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1743 send_codec_spec_.opus_max_playback_rate);
1744 return false;
stefanba4c0e42016-02-04 04:12:24 -08001745 }
1746 }
1747 }
1748
solenberg72e29d22016-03-08 06:35:16 -08001749 if (send_bitrate_setting_) {
1750 SetSendBitrateInternal(send_bitrate_bps_);
1751 }
1752
1753 // Set the CN payloadtype and the VAD status.
1754 if (send_codec_spec_.cng_payload_type != -1) {
1755 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1756 if (send_codec_spec_.cng_plfreq != 8000) {
1757 webrtc::PayloadFrequencies cn_freq;
1758 switch (send_codec_spec_.cng_plfreq) {
1759 case 16000:
1760 cn_freq = webrtc::kFreq16000Hz;
1761 break;
1762 case 32000:
1763 cn_freq = webrtc::kFreq32000Hz;
1764 break;
1765 default:
1766 RTC_NOTREACHED();
1767 return false;
1768 }
1769 if (engine()->voe()->codec()->SetSendCNPayloadType(
1770 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1771 LOG_RTCERR3(SetSendCNPayloadType, channel,
1772 send_codec_spec_.cng_payload_type, cn_freq);
1773 // TODO(ajm): This failure condition will be removed from VoE.
1774 // Restore the return here when we update to a new enough webrtc.
1775 //
1776 // Not returning false because the SetSendCNPayloadType will fail if
1777 // the channel is already sending.
1778 // This can happen if the remote description is applied twice, for
1779 // example in the case of ROAP on top of JSEP, where both side will
1780 // send the offer.
1781 }
1782 }
1783
1784 // Only turn on VAD if we have a CN payload type that matches the
1785 // clockrate for the codec we are going to use.
1786 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1787 send_codec_spec_.codec_inst.channels == 1) {
1788 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1789 // interaction between VAD and Opus FEC.
1790 LOG(LS_INFO) << "Enabling VAD";
1791 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1792 LOG_RTCERR2(SetVADStatus, channel, true);
1793 return false;
1794 }
1795 }
1796 }
solenberg0a617e22015-10-20 15:49:38 -07001797 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001798}
1799
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001800void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001802 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1804 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001805 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1807 }
1808}
1809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001811 int channel, const webrtc::CodecInst& send_codec) {
1812 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1813 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1814
solenberg72e29d22016-03-08 06:35:16 -08001815 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001816 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1817 (send_codec == current_codec)) {
1818 // Codec is already configured, we can return without setting it again.
1819 return true;
1820 }
1821
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001822 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1823 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001824 return false;
1825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 return true;
1827}
1828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1830 desired_playout_ = playout;
1831 return ChangePlayout(desired_playout_);
1832}
1833
1834bool WebRtcVoiceMediaChannel::PausePlayout() {
1835 return ChangePlayout(false);
1836}
1837
1838bool WebRtcVoiceMediaChannel::ResumePlayout() {
1839 return ChangePlayout(desired_playout_);
1840}
1841
1842bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001843 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001844 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 if (playout_ == playout) {
1846 return true;
1847 }
1848
solenberg7add0582015-11-20 09:59:34 -08001849 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001850 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001851 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001852 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001853 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 }
1855 }
solenberg1ac56142015-10-13 03:58:19 -07001856 playout_ = playout;
1857 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858}
1859
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001860void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001861 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001863 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 }
1865
solenberg246b8172015-12-08 09:50:23 -08001866 // Apply channel specific options when channel is enabled for sending.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001867 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001868 engine()->ApplyOptions(options_);
1869 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001871 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001872 for (auto& kv : send_streams_) {
1873 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001875
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001876 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877}
1878
Peter Boström0c4e06b2015-10-07 12:23:21 +02001879bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1880 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001881 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001882 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001883 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001884 // TODO(solenberg): The state change should be fully rolled back if any one of
1885 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001886 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001887 return false;
1888 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001889 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001890 return false;
1891 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001892 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001893 return SetOptions(*options);
1894 }
1895 return true;
1896}
1897
solenberg0a617e22015-10-20 15:49:38 -07001898int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1899 int id = engine()->CreateVoEChannel();
1900 if (id == -1) {
1901 LOG_RTCERR0(CreateVoEChannel);
1902 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001903 }
solenberg0a617e22015-10-20 15:49:38 -07001904 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1905 LOG_RTCERR2(RegisterExternalTransport, id, this);
1906 engine()->voe()->base()->DeleteChannel(id);
1907 return -1;
1908 }
1909 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001910}
1911
solenberg7add0582015-11-20 09:59:34 -08001912bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001913 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1914 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1915 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001916 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1917 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return false;
1919 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001920 return true;
1921}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001922
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001923bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001924 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001925 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001926 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1927
1928 uint32_t ssrc = sp.first_ssrc();
1929 RTC_DCHECK(0 != ssrc);
1930
1931 if (GetSendChannelId(ssrc) != -1) {
1932 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001933 return false;
1934 }
1935
solenberg0a617e22015-10-20 15:49:38 -07001936 // Create a new channel for sending audio data.
1937 int channel = CreateVoEChannel();
1938 if (channel == -1) {
1939 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001940 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001941
solenbergc96df772015-10-21 13:01:53 -07001942 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001943 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001944 webrtc::AudioTransport* audio_transport =
1945 engine()->voe()->base()->audio_transport();
solenberg3a941542015-11-16 07:34:50 -08001946 send_streams_.insert(std::make_pair(ssrc, new WebRtcAudioSendStream(
1947 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001948
solenberg0a617e22015-10-20 15:49:38 -07001949 // Set the current codecs to be used for the new channel. We need to do this
1950 // after adding the channel to send_channels_, because of how max bitrate is
1951 // currently being configured by SetSendCodec().
solenberg72e29d22016-03-08 06:35:16 -08001952 if (HasSendCodec() && !SetSendCodecs(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001953 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001954 return false;
1955 }
1956
1957 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001958 // the first send channel make sure that all the receive channels are updated
1959 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001960 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001961 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001962 for (const auto& stream : recv_streams_) {
1963 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001964 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001965 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001966 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001967 }
solenberg0a617e22015-10-20 15:49:38 -07001968 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1969 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1970 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001971 }
1972 }
1973
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001974 send_streams_[ssrc]->SetSend(send_);
1975 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001976}
1977
Peter Boström0c4e06b2015-10-07 12:23:21 +02001978bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001979 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001980 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001981 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1982
solenbergc96df772015-10-21 13:01:53 -07001983 auto it = send_streams_.find(ssrc);
1984 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001985 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1986 << " which doesn't exist.";
1987 return false;
1988 }
1989
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001990 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001991
solenberg7add0582015-11-20 09:59:34 -08001992 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001993 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001994 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1995 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001996 delete it->second;
1997 send_streams_.erase(it);
1998 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001999 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002000 }
solenbergc96df772015-10-21 13:01:53 -07002001 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002002 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07002003 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 return true;
2005}
2006
2007bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002008 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002009 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002010 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2011
solenberg0b675462015-10-09 01:37:09 -07002012 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002013 return false;
2014 }
2015
solenberg7add0582015-11-20 09:59:34 -08002016 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002017 if (ssrc == 0) {
2018 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2019 return false;
2020 }
2021
solenberg1ac56142015-10-13 03:58:19 -07002022 // Remove the default receive stream if one had been created with this ssrc;
2023 // we'll recreate it then.
2024 if (IsDefaultRecvStream(ssrc)) {
2025 RemoveRecvStream(ssrc);
2026 }
solenberg0b675462015-10-09 01:37:09 -07002027
solenberg7add0582015-11-20 09:59:34 -08002028 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002029 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 return false;
2031 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002034 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 return false;
2037 }
Minyue2013aec2015-05-13 14:14:42 +02002038
solenberg1ac56142015-10-13 03:58:19 -07002039 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002040 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2041 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2042 voe_codec.pltype = -1;
2043 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2044 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2045 DeleteVoEChannel(channel);
2046 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 }
2048 }
2049
solenberg1ac56142015-10-13 03:58:19 -07002050 // Only enable those configured for this channel.
2051 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002052 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002053 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002054 voe_codec.pltype = codec.id;
2055 if (engine()->voe()->codec()->SetRecPayloadType(
2056 channel, voe_codec) == -1) {
2057 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002058 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002059 return false;
2060 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002061 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 }
solenberg8fb30c32015-10-13 03:06:58 -07002063
solenberg7add0582015-11-20 09:59:34 -08002064 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2065 if (send_channel != -1) {
2066 // Associate receive channel with first send channel (so the receive channel
2067 // can obtain RTT from the send channel)
2068 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2069 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2070 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002071 }
2072
stefanba4c0e42016-02-04 04:12:24 -08002073 recv_streams_.insert(std::make_pair(
2074 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002075 recv_transport_cc_enabled_,
2076 sp.sync_label, recv_rtp_extensions_,
2077 call_)));
solenberg7add0582015-11-20 09:59:34 -08002078
solenberg72e29d22016-03-08 06:35:16 -08002079 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002080 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002081
solenberg1ac56142015-10-13 03:58:19 -07002082 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002083}
2084
Peter Boström0c4e06b2015-10-07 12:23:21 +02002085bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002086 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002087 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002088 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2089
solenberg7add0582015-11-20 09:59:34 -08002090 const auto it = recv_streams_.find(ssrc);
2091 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002092 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2093 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002094 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002095 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002096
solenberg1ac56142015-10-13 03:58:19 -07002097 // Deregister default channel, if that's the one being destroyed.
2098 if (IsDefaultRecvStream(ssrc)) {
2099 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002101
solenberg7add0582015-11-20 09:59:34 -08002102 const int channel = it->second->channel();
2103
2104 // Clean up and delete the receive stream+channel.
2105 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002106 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002107 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002108 delete it->second;
2109 recv_streams_.erase(it);
2110 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002111}
2112
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002113bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2114 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002115 auto it = send_streams_.find(ssrc);
2116 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002117 if (source) {
2118 // Return an error if trying to set a valid source with an invalid ssrc.
2119 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002120 return false;
2121 }
2122
2123 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002124 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002125 }
2126
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002127 if (source) {
2128 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002129 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002130 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002131 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 return true;
2134}
2135
2136bool WebRtcVoiceMediaChannel::GetActiveStreams(
2137 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002138 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002140 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002141 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002143 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 }
2145 }
2146 return true;
2147}
2148
2149int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002150 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002151 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002152 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002153 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 }
2155 return highest;
2156}
2157
2158int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2159 int ret;
2160 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2161 // In case of error, log the info and continue
2162 LOG_RTCERR0(TimeSinceLastTyping);
2163 ret = -1;
2164 } else {
2165 ret *= 1000; // We return ms, webrtc returns seconds.
2166 }
2167 return ret;
2168}
2169
2170void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2171 int cost_per_typing, int reporting_threshold, int penalty_decay,
2172 int type_event_delay) {
2173 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2174 time_window, cost_per_typing,
2175 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2176 // In case of error, log the info and continue
2177 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2178 cost_per_typing, reporting_threshold, penalty_decay,
2179 type_event_delay);
2180 }
2181}
2182
solenberg4bac9c52015-10-09 02:32:53 -07002183bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002184 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002185 if (ssrc == 0) {
2186 default_recv_volume_ = volume;
2187 if (default_recv_ssrc_ == -1) {
2188 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 }
solenberg1ac56142015-10-13 03:58:19 -07002190 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2191 }
2192 int ch_id = GetReceiveChannelId(ssrc);
2193 if (ch_id < 0) {
2194 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2195 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196 }
2197
solenberg1ac56142015-10-13 03:58:19 -07002198 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2199 volume)) {
2200 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2201 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 }
solenberg1ac56142015-10-13 03:58:19 -07002203 LOG(LS_INFO) << "SetOutputVolume to " << volume
2204 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 return true;
2206}
2207
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002209 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210}
2211
solenberg1d63dd02015-12-02 12:35:09 -08002212bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2213 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002214 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002215 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2216 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 return false;
2218 }
2219
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002220 // Figure out which WebRtcAudioSendStream to send the event on.
2221 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2222 if (it == send_streams_.end()) {
2223 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002224 return false;
2225 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002226 if (event < kMinTelephoneEventCode ||
2227 event > kMaxTelephoneEventCode) {
2228 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002229 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002231 if (duration < kMinTelephoneEventDuration ||
2232 duration > kMaxTelephoneEventDuration) {
2233 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2234 return false;
2235 }
2236 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237}
2238
wu@webrtc.orga9890802013-12-13 00:21:03 +00002239void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002240 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002241 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002242
solenberg1ac56142015-10-13 03:58:19 -07002243 uint32_t ssrc = 0;
2244 if (!GetRtpSsrc(packet->data(), packet->size(), &ssrc)) {
2245 return;
2246 }
2247
solenberg7e63ef02015-11-20 00:19:43 -08002248 // If we don't have a default channel, and the SSRC is unknown, create a
2249 // default channel.
2250 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002251 StreamParams sp;
2252 sp.ssrcs.push_back(ssrc);
2253 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2254 if (!AddRecvStream(sp)) {
2255 LOG(LS_WARNING) << "Could not create default receive stream.";
2256 return;
2257 }
2258 default_recv_ssrc_ = ssrc;
2259 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002260 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002261 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002262 new ProxySink(default_sink_.get()));
2263 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2264 }
solenberg1ac56142015-10-13 03:58:19 -07002265 }
2266
2267 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002268 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2269 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002270 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2271 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2272 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2273 webrtc_packet_time);
2274 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002275 // If the SSRC is unknown here, route it to the default channel, if we have
2276 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2277 if (default_recv_ssrc_ == -1) {
2278 return;
2279 } else {
2280 ssrc = default_recv_ssrc_;
2281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 }
2283
solenberg1ac56142015-10-13 03:58:19 -07002284 // Find the channel to send this packet to. It must exist since webrtc::Call
2285 // was able to demux the packet.
2286 int channel = GetReceiveChannelId(ssrc);
2287 RTC_DCHECK(channel != -1);
2288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002290 engine()->voe()->network()->ReceivedRTPPacket(
solenberg1ac56142015-10-13 03:58:19 -07002291 channel, packet->data(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292}
2293
wu@webrtc.orga9890802013-12-13 00:21:03 +00002294void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002295 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002296 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002297
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002298 // Forward packet to Call as well.
2299 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2300 packet_time.not_before);
2301 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2302 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2303 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002304
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002305 // Sending channels need all RTCP packets with feedback information.
2306 // Even sender reports can contain attached report blocks.
2307 // Receiving channels need sender reports in order to create
2308 // correct receiver reports.
2309 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002310 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002311 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2312 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002313 }
2314
solenberg0b675462015-10-09 01:37:09 -07002315 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002316 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002317 uint32_t ssrc = 0;
2318 if (!GetRtcpSsrc(packet->data(), packet->size(), &ssrc)) {
2319 return;
2320 }
2321 int recv_channel_id = GetReceiveChannelId(ssrc);
2322 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002323 engine()->voe()->network()->ReceivedRTCPPacket(
solenberg0b675462015-10-09 01:37:09 -07002324 recv_channel_id, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002325 }
2326 }
2327
2328 // SR may continue RR and any RR entry may correspond to any one of the send
2329 // channels. So all RTCP packets must be forwarded all send channels. VoE
2330 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002331 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002332 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002333 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335}
2336
Peter Boström0c4e06b2015-10-07 12:23:21 +02002337bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002338 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002339 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002340 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2342 return false;
2343 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2345 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 return false;
2347 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002348 // We set the AGC to mute state only when all the channels are muted.
2349 // This implementation is not ideal, instead we should signal the AGC when
2350 // the mic channel is muted/unmuted. We can't do it today because there
2351 // is no good way to know which stream is mapping to the mic channel.
2352 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002353 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002354 if (!all_muted) {
2355 break;
2356 }
2357 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002358 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002359 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002360 return false;
2361 }
2362 }
2363
2364 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002365 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002366 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002367 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368 return true;
2369}
2370
minyue@webrtc.org26236952014-10-29 02:27:08 +00002371// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2372// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002373bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002374 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
minyue@webrtc.org26236952014-10-29 02:27:08 +00002375 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002376}
2377
minyue@webrtc.org26236952014-10-29 02:27:08 +00002378bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2379 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002380
minyue@webrtc.org26236952014-10-29 02:27:08 +00002381 send_bitrate_setting_ = true;
2382 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002383
solenberg72e29d22016-03-08 06:35:16 -08002384 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002385 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002386 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002387 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388 }
2389
minyue@webrtc.org26236952014-10-29 02:27:08 +00002390 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002391 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2392 // SetMaxSendBandwith(0), the second call removes the previous limit.
2393 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394 return true;
2395
solenberg72e29d22016-03-08 06:35:16 -08002396 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002397 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398
2399 if (is_multi_rate) {
2400 // If codec is multi-rate then just set the bitrate.
2401 codec.rate = bps;
solenbergc96df772015-10-21 13:01:53 -07002402 for (const auto& ch : send_streams_) {
solenberg0a617e22015-10-20 15:49:38 -07002403 if (!SetSendCodec(ch.second->channel(), codec)) {
2404 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2405 << " to bitrate " << bps << " bps.";
2406 return false;
2407 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408 }
2409 return true;
2410 } else {
2411 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2412 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2413 // fixed bitrate then ignore.
2414 if (bps < codec.rate) {
2415 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2416 << " to bitrate " << bps << " bps"
2417 << ", requires at least " << codec.rate << " bps.";
2418 return false;
2419 }
2420 return true;
2421 }
2422}
2423
2424bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002425 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002426 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002427 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002428
solenberg85a04962015-10-27 03:35:21 -07002429 // Get SSRC and stats for each sender.
2430 RTC_DCHECK(info->senders.size() == 0);
2431 for (const auto& stream : send_streams_) {
2432 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002433 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002434 sinfo.add_ssrc(stats.local_ssrc);
2435 sinfo.bytes_sent = stats.bytes_sent;
2436 sinfo.packets_sent = stats.packets_sent;
2437 sinfo.packets_lost = stats.packets_lost;
2438 sinfo.fraction_lost = stats.fraction_lost;
2439 sinfo.codec_name = stats.codec_name;
2440 sinfo.ext_seqnum = stats.ext_seqnum;
2441 sinfo.jitter_ms = stats.jitter_ms;
2442 sinfo.rtt_ms = stats.rtt_ms;
2443 sinfo.audio_level = stats.audio_level;
2444 sinfo.aec_quality_min = stats.aec_quality_min;
2445 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2446 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2447 sinfo.echo_return_loss = stats.echo_return_loss;
2448 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002449 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 }
2452
solenberg85a04962015-10-27 03:35:21 -07002453 // Get SSRC and stats for each receiver.
2454 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002455 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002456 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2457 VoiceReceiverInfo rinfo;
2458 rinfo.add_ssrc(stats.remote_ssrc);
2459 rinfo.bytes_rcvd = stats.bytes_rcvd;
2460 rinfo.packets_rcvd = stats.packets_rcvd;
2461 rinfo.packets_lost = stats.packets_lost;
2462 rinfo.fraction_lost = stats.fraction_lost;
2463 rinfo.codec_name = stats.codec_name;
2464 rinfo.ext_seqnum = stats.ext_seqnum;
2465 rinfo.jitter_ms = stats.jitter_ms;
2466 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2467 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2468 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2469 rinfo.audio_level = stats.audio_level;
2470 rinfo.expand_rate = stats.expand_rate;
2471 rinfo.speech_expand_rate = stats.speech_expand_rate;
2472 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2473 rinfo.accelerate_rate = stats.accelerate_rate;
2474 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2475 rinfo.decoding_calls_to_silence_generator =
2476 stats.decoding_calls_to_silence_generator;
2477 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2478 rinfo.decoding_normal = stats.decoding_normal;
2479 rinfo.decoding_plc = stats.decoding_plc;
2480 rinfo.decoding_cng = stats.decoding_cng;
2481 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2482 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2483 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484 }
2485
2486 return true;
2487}
2488
Tommif888bb52015-12-12 01:37:01 +01002489void WebRtcVoiceMediaChannel::SetRawAudioSink(
2490 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002491 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002492 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002493 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2494 << " " << (sink ? "(ptr)" : "NULL");
2495 if (ssrc == 0) {
2496 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002497 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002498 sink ? new ProxySink(sink.get()) : nullptr);
2499 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2500 }
2501 default_sink_ = std::move(sink);
2502 return;
2503 }
Tommif888bb52015-12-12 01:37:01 +01002504 const auto it = recv_streams_.find(ssrc);
2505 if (it == recv_streams_.end()) {
2506 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2507 return;
2508 }
deadbeef2d110be2016-01-13 12:00:26 -08002509 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002510}
2511
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002513 unsigned int ulevel = 0;
2514 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2516}
2517
Peter Boström0c4e06b2015-10-07 12:23:21 +02002518int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002519 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002520 const auto it = recv_streams_.find(ssrc);
2521 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002522 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002523 }
solenberg1ac56142015-10-13 03:58:19 -07002524 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002525}
2526
Peter Boström0c4e06b2015-10-07 12:23:21 +02002527int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002528 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002529 const auto it = send_streams_.find(ssrc);
2530 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002531 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002532 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002533 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534}
2535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2537 if (playout) {
2538 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2539 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2540 LOG_RTCERR1(StartPlayout, channel);
2541 return false;
2542 }
2543 } else {
2544 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2545 engine()->voe()->base()->StopPlayout(channel);
2546 }
2547 return true;
2548}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549} // namespace cricket
2550
2551#endif // HAVE_WEBRTC_VOICE