blob: f57db27a3177f494813af1465657fcc6a7dfd074 [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
deadbeef884f5852016-01-15 09:20:04 -0800102class ProxySink : public webrtc::AudioSinkInterface {
103 public:
104 ProxySink(AudioSinkInterface* sink) : sink_(sink) { RTC_DCHECK(sink); }
105
106 void OnData(const Data& audio) override { sink_->OnData(audio); }
107
108 private:
109 webrtc::AudioSinkInterface* sink_;
110};
111
solenberg0b675462015-10-09 01:37:09 -0700112bool ValidateStreamParams(const StreamParams& sp) {
113 if (sp.ssrcs.empty()) {
114 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
115 return false;
116 }
117 if (sp.ssrcs.size() > 1) {
118 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
119 return false;
120 }
121 return true;
122}
123
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700125std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000126 std::stringstream ss;
127 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
128 << " (" << codec.id << ")";
129 return ss.str();
130}
Minyue Li7100dcd2015-03-27 05:05:59 +0100131
solenbergd97ec302015-10-07 01:40:33 -0700132std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 std::stringstream ss;
134 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
135 << " (" << codec.pltype << ")";
136 return ss.str();
137}
138
solenbergd97ec302015-10-07 01:40:33 -0700139bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100140 return (_stricmp(codec.name.c_str(), ref_name) == 0);
141}
142
solenbergd97ec302015-10-07 01:40:33 -0700143bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100144 return (_stricmp(codec.plname, ref_name) == 0);
145}
146
solenbergd97ec302015-10-07 01:40:33 -0700147bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800148 const AudioCodec& codec,
149 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200150 for (const AudioCodec& c : codecs) {
151 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200153 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154 }
155 return true;
156 }
157 }
158 return false;
159}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000160
solenberg0b675462015-10-09 01:37:09 -0700161bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
162 if (codecs.empty()) {
163 return true;
164 }
165 std::vector<int> payload_types;
166 for (const AudioCodec& codec : codecs) {
167 payload_types.push_back(codec.id);
168 }
169 std::sort(payload_types.begin(), payload_types.end());
170 auto it = std::unique(payload_types.begin(), payload_types.end());
171 return it == payload_types.end();
172}
173
Minyue Li7100dcd2015-03-27 05:05:59 +0100174// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800175bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100176 int value;
177 return codec.GetParam(feature, &value) && value == 1;
178}
179
180// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
181// otherwise. If the value (either from params or codec.bitrate) <=0, use the
182// default configuration. If the value is beyond feasible bit rate of Opus,
183// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700184int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100185 int bitrate = 0;
186 bool use_param = true;
187 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
188 bitrate = codec.bitrate;
189 use_param = false;
190 }
191 if (bitrate <= 0) {
192 if (max_playback_rate <= 8000) {
193 bitrate = kOpusBitrateNb;
194 } else if (max_playback_rate <= 16000) {
195 bitrate = kOpusBitrateWb;
196 } else {
197 bitrate = kOpusBitrateFb;
198 }
199
200 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
201 bitrate *= 2;
202 }
203 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
204 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
205 std::string rate_source =
206 use_param ? "Codec parameter \"maxaveragebitrate\"" :
207 "Supplied Opus bitrate";
208 LOG(LS_WARNING) << rate_source
209 << " is invalid and is replaced by: "
210 << bitrate;
211 }
212 return bitrate;
213}
214
215// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
216// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700217int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100218 int value;
219 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
220 return value;
221 }
222 return kOpusDefaultMaxPlaybackRate;
223}
224
solenbergd97ec302015-10-07 01:40:33 -0700225void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100226 bool* enable_codec_fec, int* max_playback_rate,
227 bool* enable_codec_dtx) {
228 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
229 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
230 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
231
232 // If OPUS, change what we send according to the "stereo" codec
233 // parameter, and not the "channels" parameter. We set
234 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
235 // the bitrate is not specified, i.e. is <= zero, we set it to the
236 // appropriate default value for mono or stereo Opus.
237
238 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
239 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
240}
241
solenberg566ef242015-11-06 15:34:49 -0800242webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
243 webrtc::AudioState::Config config;
244 config.voice_engine = voe_wrapper->engine();
245 return config;
246}
247
solenberg26c8c912015-11-27 04:00:25 -0800248class WebRtcVoiceCodecs final {
249 public:
250 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
251 // list and add a test which verifies VoE supports the listed codecs.
252 static std::vector<AudioCodec> SupportedCodecs() {
253 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
254 std::vector<AudioCodec> result;
255 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
256 // Change the sample rate of G722 to 8000 to match SDP.
257 MaybeFixupG722(&voe_codec, 8000);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000258 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100259 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000260 continue;
261 }
262
263 const CodecPref* pref = NULL;
tfarina5237aaf2015-11-10 23:44:30 -0800264 for (size_t j = 0; j < arraysize(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100265 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000266 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
267 kCodecPrefs[j].channels == voe_codec.channels) {
268 pref = &kCodecPrefs[j];
269 break;
270 }
271 }
272
273 if (pref) {
274 // Use the payload type that we've configured in our pref table;
275 // use the offset in our pref table to determine the sort order.
tfarina5237aaf2015-11-10 23:44:30 -0800276 AudioCodec codec(
277 pref->payload_type, voe_codec.plname, voe_codec.plfreq,
278 voe_codec.rate, voe_codec.channels,
279 static_cast<int>(arraysize(kCodecPrefs)) - (pref - kCodecPrefs));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000280 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100281 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000282 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000283 codec.bitrate = 0;
284 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100285 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000286 // Only add fmtp parameters that differ from the spec.
287 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
288 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000289 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000290 }
291 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
292 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000293 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000294 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000295 codec.SetParam(kCodecParamUseInbandFec, 1);
stefanba4c0e42016-02-04 04:12:24 -0800296 codec.AddFeedbackParam(
297 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000298
299 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000300 // when they can be set to values other than the default.
301 }
solenberg26c8c912015-11-27 04:00:25 -0800302 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000303 } else {
304 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
305 }
306 }
solenberg26c8c912015-11-27 04:00:25 -0800307 // Make sure they are in local preference order.
308 std::sort(result.begin(), result.end(), &AudioCodec::Preferable);
309 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000310 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000311
solenberg26c8c912015-11-27 04:00:25 -0800312 static bool ToCodecInst(const AudioCodec& in,
313 webrtc::CodecInst* out) {
314 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
315 // Change the sample rate of G722 to 8000 to match SDP.
316 MaybeFixupG722(&voe_codec, 8000);
317 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
318 voe_codec.rate, voe_codec.channels, 0);
319 bool multi_rate = IsCodecMultiRate(voe_codec);
320 // Allow arbitrary rates for ISAC to be specified.
321 if (multi_rate) {
322 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
323 codec.bitrate = 0;
324 }
325 if (codec.Matches(in)) {
326 if (out) {
327 // Fixup the payload type.
328 voe_codec.pltype = in.id;
329
330 // Set bitrate if specified.
331 if (multi_rate && in.bitrate != 0) {
332 voe_codec.rate = in.bitrate;
333 }
334
335 // Reset G722 sample rate to 16000 to match WebRTC.
336 MaybeFixupG722(&voe_codec, 16000);
337
338 // Apply codec-specific settings.
339 if (IsCodec(codec, kIsacCodecName)) {
340 // If ISAC and an explicit bitrate is not specified,
341 // enable auto bitrate adjustment.
342 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
343 }
344 *out = voe_codec;
345 }
346 return true;
347 }
348 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000349 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000350 }
solenberg26c8c912015-11-27 04:00:25 -0800351
352 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
353 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
354 if (IsCodec(codec, kCodecPrefs[i].name) &&
355 kCodecPrefs[i].clockrate == codec.plfreq) {
356 return kCodecPrefs[i].is_multi_rate;
357 }
358 }
359 return false;
360 }
361
362 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
363 // codec pacsize if it's valid, or we will pick the next smallest value we
364 // support.
365 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
366 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
367 for (const CodecPref& codec_pref : kCodecPrefs) {
368 if ((IsCodec(*codec, codec_pref.name) &&
369 codec_pref.clockrate == codec->plfreq) ||
370 IsCodec(*codec, kG722CodecName)) {
371 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
372 if (packet_size_ms) {
373 // Convert unit from milli-seconds to samples.
374 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
375 return true;
376 }
377 }
378 }
379 return false;
380 }
381
stefanba4c0e42016-02-04 04:12:24 -0800382 static const AudioCodec* GetPreferredCodec(
383 const std::vector<AudioCodec>& codecs,
solenberg72e29d22016-03-08 06:35:16 -0800384 webrtc::CodecInst* out,
stefanba4c0e42016-02-04 04:12:24 -0800385 int* red_payload_type) {
solenberg72e29d22016-03-08 06:35:16 -0800386 RTC_DCHECK(out);
stefanba4c0e42016-02-04 04:12:24 -0800387 RTC_DCHECK(red_payload_type);
388 // Select the preferred send codec (the first non-telephone-event/CN codec).
389 for (const AudioCodec& codec : codecs) {
390 *red_payload_type = -1;
391 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
392 // Skip telephone-event/CN codec, which will be handled later.
393 continue;
394 }
395
396 // We'll use the first codec in the list to actually send audio data.
397 // Be sure to use the payload type requested by the remote side.
398 // "red", for RED audio, is a special case where the actual codec to be
399 // used is specified in params.
400 const AudioCodec* found_codec = &codec;
401 if (IsCodec(*found_codec, kRedCodecName)) {
402 // Parse out the RED parameters. If we fail, just ignore RED;
403 // we don't support all possible params/usage scenarios.
404 *red_payload_type = codec.id;
405 found_codec = GetRedSendCodec(*found_codec, codecs);
406 if (!found_codec) {
407 continue;
408 }
409 }
410 // Ignore codecs we don't know about. The negotiation step should prevent
411 // this, but double-check to be sure.
solenberg72e29d22016-03-08 06:35:16 -0800412 webrtc::CodecInst voe_codec = {0};
413 if (!ToCodecInst(*found_codec, &voe_codec)) {
stefanba4c0e42016-02-04 04:12:24 -0800414 LOG(LS_WARNING) << "Unknown codec " << ToString(*found_codec);
415 continue;
416 }
solenberg72e29d22016-03-08 06:35:16 -0800417 *out = voe_codec;
stefanba4c0e42016-02-04 04:12:24 -0800418 return found_codec;
419 }
420 return nullptr;
421 }
422
solenberg26c8c912015-11-27 04:00:25 -0800423 private:
424 static const int kMaxNumPacketSize = 6;
425 struct CodecPref {
426 const char* name;
427 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800428 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800429 int payload_type;
430 bool is_multi_rate;
431 int packet_sizes_ms[kMaxNumPacketSize];
432 };
433 // Note: keep the supported packet sizes in ascending order.
434 static const CodecPref kCodecPrefs[12];
435
436 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
437 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
438 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
439 if (packet_size_ms && packet_size_ms <= ptime_ms) {
440 selected_packet_size_ms = packet_size_ms;
441 }
442 }
443 return selected_packet_size_ms;
444 }
445
446 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
447 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
448 // codec.
449 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
450 if (IsCodec(*voe_codec, kG722CodecName)) {
451 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
452 // has changed, and this special case is no longer needed.
453 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
454 voe_codec->plfreq = new_plfreq;
455 }
456 }
stefanba4c0e42016-02-04 04:12:24 -0800457
458 static const AudioCodec* GetRedSendCodec(
459 const AudioCodec& red_codec,
460 const std::vector<AudioCodec>& all_codecs) {
461 // Get the RED encodings from the parameter with no name. This may
462 // change based on what is discussed on the Jingle list.
463 // The encoding parameter is of the form "a/b"; we only support where
464 // a == b. Verify this and parse out the value into red_pt.
465 // If the parameter value is absent (as it will be until we wire up the
466 // signaling of this message), use the second codec specified (i.e. the
467 // one after "red") as the encoding parameter.
468 int red_pt = -1;
469 std::string red_params;
470 CodecParameterMap::const_iterator it = red_codec.params.find("");
471 if (it != red_codec.params.end()) {
472 red_params = it->second;
473 std::vector<std::string> red_pts;
474 if (rtc::split(red_params, '/', &red_pts) != 2 ||
475 red_pts[0] != red_pts[1] || !rtc::FromString(red_pts[0], &red_pt)) {
476 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
477 return nullptr;
478 }
479 } else if (red_codec.params.empty()) {
480 LOG(LS_WARNING) << "RED params not present, using defaults";
481 if (all_codecs.size() > 1) {
482 red_pt = all_codecs[1].id;
483 }
484 }
485
486 // Try to find red_pt in |codecs|.
487 for (const AudioCodec& codec : all_codecs) {
488 if (codec.id == red_pt) {
489 return &codec;
490 }
491 }
492 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
493 return nullptr;
494 }
solenberg26c8c912015-11-27 04:00:25 -0800495};
496
497const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
498 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
499 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
500 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
501 // G722 should be advertised as 8000 Hz because of the RFC "bug".
502 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
503 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
504 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
505 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
506 { kCnCodecName, 32000, 1, 106, false, { } },
507 { kCnCodecName, 16000, 1, 105, false, { } },
508 { kCnCodecName, 8000, 1, 13, false, { } },
509 { kRedCodecName, 8000, 1, 127, false, { } },
510 { kDtmfCodecName, 8000, 1, 126, false, { } },
511};
512} // namespace {
513
514bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
515 webrtc::CodecInst* out) {
516 return WebRtcVoiceCodecs::ToCodecInst(in, out);
517}
518
519WebRtcVoiceEngine::WebRtcVoiceEngine()
520 : voe_wrapper_(new VoEWrapper()),
521 audio_state_(webrtc::AudioState::Create(MakeAudioStateConfig(voe()))) {
522 Construct();
523}
524
525WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper)
526 : voe_wrapper_(voe_wrapper) {
527 Construct();
528}
529
530void WebRtcVoiceEngine::Construct() {
531 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
532 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
533
534 signal_thread_checker_.DetachFromThread();
535 std::memset(&default_agc_config_, 0, sizeof(default_agc_config_));
solenberg246b8172015-12-08 09:50:23 -0800536 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
solenberg26c8c912015-11-27 04:00:25 -0800537
538 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
539 webrtc::Trace::SetTraceCallback(this);
540
541 // Load our audio codec list.
542 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000543}
544
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800546 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000547 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000548 if (adm_) {
549 voe_wrapper_.reset();
550 adm_->Release();
551 adm_ = NULL;
552 }
solenbergbd138382015-11-20 16:08:07 -0800553 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000554}
555
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000556bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
solenberg566ef242015-11-06 15:34:49 -0800557 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700558 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000559 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
560 bool res = InitInternal();
561 if (res) {
562 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
563 } else {
564 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
565 Terminate();
566 }
567 return res;
568}
569
570bool WebRtcVoiceEngine::InitInternal() {
solenberg566ef242015-11-06 15:34:49 -0800571 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg72e29d22016-03-08 06:35:16 -0800572 // Temporarily turn logging level up for the Init call.
solenbergbd138382015-11-20 16:08:07 -0800573 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800574 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000575 if (voe_wrapper_->base()->Init(adm_) == -1) {
576 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000577 return false;
578 }
solenbergbd138382015-11-20 16:08:07 -0800579 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000580
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000581 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800582 // calling ApplyOptions or the default will be overwritten.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000583 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
584 LOG_RTCERR0(GetAgcConfig);
585 return false;
586 }
587
solenberg0f7d2932016-01-15 01:40:39 -0800588 // Set default engine options.
589 {
590 AudioOptions options;
591 options.echo_cancellation = rtc::Optional<bool>(true);
592 options.auto_gain_control = rtc::Optional<bool>(true);
593 options.noise_suppression = rtc::Optional<bool>(true);
594 options.highpass_filter = rtc::Optional<bool>(true);
595 options.stereo_swapping = rtc::Optional<bool>(false);
596 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
597 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
598 options.typing_detection = rtc::Optional<bool>(true);
599 options.adjust_agc_delta = rtc::Optional<int>(0);
600 options.experimental_agc = rtc::Optional<bool>(false);
601 options.extended_filter_aec = rtc::Optional<bool>(false);
602 options.delay_agnostic_aec = rtc::Optional<bool>(false);
603 options.experimental_ns = rtc::Optional<bool>(false);
solenberg0f7d2932016-01-15 01:40:39 -0800604 if (!ApplyOptions(options)) {
605 return false;
606 }
607 }
608
solenberg72e29d22016-03-08 06:35:16 -0800609 // Print our codec list again for the call diagnostic log.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000610 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200611 for (const AudioCodec& codec : codecs_) {
612 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000613 }
614
solenberg246b8172015-12-08 09:50:23 -0800615 SetDefaultDevices();
616
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000617 initialized_ = true;
618 return true;
619}
620
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000621void WebRtcVoiceEngine::Terminate() {
solenberg566ef242015-11-06 15:34:49 -0800622 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000623 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
624 initialized_ = false;
625
626 StopAecDump();
627
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000628 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000629}
630
solenberg566ef242015-11-06 15:34:49 -0800631rtc::scoped_refptr<webrtc::AudioState>
632 WebRtcVoiceEngine::GetAudioState() const {
633 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
634 return audio_state_;
635}
636
nisse51542be2016-02-12 02:27:06 -0800637VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
638 webrtc::Call* call,
639 const MediaConfig& config,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200640 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800641 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisse51542be2016-02-12 02:27:06 -0800642 return new WebRtcVoiceMediaChannel(this, config, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000643}
644
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000645bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800646 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikac14f5ff2015-09-23 14:08:33 +0200647 LOG(LS_INFO) << "ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800648 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800649
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000650 // kEcConference is AEC with high suppression.
651 webrtc::EcModes ec_mode = webrtc::kEcConference;
652 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
653 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
654 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700655 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000656 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700657 << *options.aecm_generate_comfort_noise
658 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000659 }
660
kjellanderfcfc8042016-01-14 11:01:09 -0800661#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000662 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100663 options.echo_cancellation = rtc::Optional<bool>(false);
664 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200665 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000666#elif defined(ANDROID)
667 ec_mode = webrtc::kEcAecm;
668#endif
669
kjellanderfcfc8042016-01-14 11:01:09 -0800670#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000671 // Set the AGC mode for iOS as well despite disabling it above, to avoid
672 // unsupported configuration errors from webrtc.
673 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100674 options.typing_detection = rtc::Optional<bool>(false);
675 options.experimental_agc = rtc::Optional<bool>(false);
676 options.extended_filter_aec = rtc::Optional<bool>(false);
677 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000678#endif
679
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100680 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
681 // where the feature is not supported.
682 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800683#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700684 if (options.delay_agnostic_aec) {
685 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100686 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100687 options.echo_cancellation = rtc::Optional<bool>(true);
688 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100689 ec_mode = webrtc::kEcConference;
690 }
691 }
692#endif
693
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000694 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
695
kwiberg102c6a62015-10-30 02:47:38 -0700696 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000697 // Check if platform supports built-in EC. Currently only supported on
698 // Android and in combination with Java based audio layer.
699 // TODO(henrika): investigate possibility to support built-in EC also
700 // in combination with Open SL ES audio.
701 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200702 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200703 // Built-in EC exists on this device and use_delay_agnostic_aec is not
704 // overriding it. Enable/Disable it according to the echo_cancellation
705 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200706 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700707 *options.echo_cancellation && !use_delay_agnostic_aec;
Bjorn Volcker73f72102015-06-03 14:50:15 +0200708 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
709 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100710 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000711 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100712 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000713 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
714 }
715 }
kwiberg102c6a62015-10-30 02:47:38 -0700716 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
717 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000718 return false;
719 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700720 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200721 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000722 }
723#if !defined(ANDROID)
724 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700725 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
726 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000727 return false;
728 }
729#endif
730 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700731 bool cn = options.aecm_generate_comfort_noise.value_or(false);
732 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
733 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000734 return false;
735 }
736 }
737 }
738
kwiberg102c6a62015-10-30 02:47:38 -0700739 if (options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200740 const bool built_in_agc = voe_wrapper_->hw()->BuiltInAGCIsAvailable();
741 if (built_in_agc) {
kwiberg102c6a62015-10-30 02:47:38 -0700742 if (voe_wrapper_->hw()->EnableBuiltInAGC(*options.auto_gain_control) ==
743 0 &&
744 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200745 // Disable internal software AGC if built-in AGC is enabled,
746 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100747 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200748 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
749 }
750 }
kwiberg102c6a62015-10-30 02:47:38 -0700751 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
752 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000753 return false;
754 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700755 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
756 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000757 }
758 }
759
kwiberg102c6a62015-10-30 02:47:38 -0700760 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
761 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000762 // Override default_agc_config_. Generally, an unset option means "leave
763 // the VoE bits alone" in this function, so we want whatever is set to be
764 // stored as the new "default". If we didn't, then setting e.g.
765 // tx_agc_target_dbov would reset digital compression gain and limiter
766 // settings.
767 // Also, if we don't update default_agc_config_, then adjust_agc_delta
768 // would be an offset from the original values, and not whatever was set
769 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700770 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
771 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000772 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700773 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000774 default_agc_config_.digitalCompressionGaindB);
775 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700776 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000777 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
778 LOG_RTCERR3(SetAgcConfig,
779 default_agc_config_.targetLeveldBOv,
780 default_agc_config_.digitalCompressionGaindB,
781 default_agc_config_.limiterEnable);
782 return false;
783 }
784 }
785
kwiberg102c6a62015-10-30 02:47:38 -0700786 if (options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200787 const bool built_in_ns = voe_wrapper_->hw()->BuiltInNSIsAvailable();
788 if (built_in_ns) {
kwiberg102c6a62015-10-30 02:47:38 -0700789 if (voe_wrapper_->hw()->EnableBuiltInNS(*options.noise_suppression) ==
790 0 &&
791 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200792 // Disable internal software NS if built-in NS is enabled,
793 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100794 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200795 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
796 }
797 }
kwiberg102c6a62015-10-30 02:47:38 -0700798 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
799 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000800 return false;
801 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700802 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200803 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000804 }
805 }
806
kwiberg102c6a62015-10-30 02:47:38 -0700807 if (options.highpass_filter) {
808 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
809 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
810 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000811 return false;
812 }
813 }
814
kwiberg102c6a62015-10-30 02:47:38 -0700815 if (options.stereo_swapping) {
816 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
817 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
818 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
819 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000820 return false;
821 }
822 }
823
kwiberg102c6a62015-10-30 02:47:38 -0700824 if (options.audio_jitter_buffer_max_packets) {
825 LOG(LS_INFO) << "NetEq capacity is "
826 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200827 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700828 new webrtc::NetEqCapacityConfig(
829 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200830 }
831
kwiberg102c6a62015-10-30 02:47:38 -0700832 if (options.audio_jitter_buffer_fast_accelerate) {
833 LOG(LS_INFO) << "NetEq fast mode? "
834 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200835 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700836 new webrtc::NetEqFastAccelerate(
837 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200838 }
839
kwiberg102c6a62015-10-30 02:47:38 -0700840 if (options.typing_detection) {
841 LOG(LS_INFO) << "Typing detection is enabled? "
842 << *options.typing_detection;
843 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000844 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700845 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000846 }
847 }
848
kwiberg102c6a62015-10-30 02:47:38 -0700849 if (options.adjust_agc_delta) {
850 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
851 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000852 return false;
853 }
854 }
855
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000856 webrtc::Config config;
857
kwiberg102c6a62015-10-30 02:47:38 -0700858 if (options.delay_agnostic_aec)
859 delay_agnostic_aec_ = options.delay_agnostic_aec;
860 if (delay_agnostic_aec_) {
861 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700862 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700863 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100864 }
865
kwiberg102c6a62015-10-30 02:47:38 -0700866 if (options.extended_filter_aec) {
867 extended_filter_aec_ = options.extended_filter_aec;
868 }
869 if (extended_filter_aec_) {
870 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200871 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700872 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000873 }
874
kwiberg102c6a62015-10-30 02:47:38 -0700875 if (options.experimental_ns) {
876 experimental_ns_ = options.experimental_ns;
877 }
878 if (experimental_ns_) {
879 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000880 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700881 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000882 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000883
884 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
885 // returns NULL on audio_processing().
886 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
887 if (audioproc) {
888 audioproc->SetExtraOptions(config);
889 }
890
kwiberg102c6a62015-10-30 02:47:38 -0700891 if (options.recording_sample_rate) {
892 LOG(LS_INFO) << "Recording sample rate is "
893 << *options.recording_sample_rate;
894 if (voe_wrapper_->hw()->SetRecordingSampleRate(
895 *options.recording_sample_rate)) {
896 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000897 }
898 }
899
kwiberg102c6a62015-10-30 02:47:38 -0700900 if (options.playout_sample_rate) {
901 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
902 if (voe_wrapper_->hw()->SetPlayoutSampleRate(
903 *options.playout_sample_rate)) {
904 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000905 }
906 }
907
908 return true;
909}
910
solenberg246b8172015-12-08 09:50:23 -0800911void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800912 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800913#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800914 int in_id = kDefaultAudioDeviceId;
915 int out_id = kDefaultAudioDeviceId;
916 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
917 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000918
solenbergc1a1b352015-09-22 13:31:20 -0700919 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800920 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
921 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000922 ret = false;
923 }
solenberg246b8172015-12-08 09:50:23 -0800924 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
925 if (ap) {
926 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 }
928
solenberg246b8172015-12-08 09:50:23 -0800929 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
930 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 ret = false;
932 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800935 LOG(LS_INFO) << "Set microphone to (id=" << in_id
936 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 }
kjellanderfcfc8042016-01-14 11:01:09 -0800938#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939}
940
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800942 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 unsigned int ulevel;
944 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
945 LOG_RTCERR1(GetSpeakerVolume, level);
946 return false;
947 }
948 *level = ulevel;
949 return true;
950}
951
952bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800953 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700954 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
956 LOG_RTCERR1(SetSpeakerVolume, level);
957 return false;
958 }
959 return true;
960}
961
962int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800963 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964 unsigned int ulevel;
965 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
966 static_cast<int>(ulevel) : -1;
967}
968
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800970 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 return codecs_;
972}
973
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100974RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800975 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100976 RtpCapabilities capabilities;
977 capabilities.header_extensions.push_back(RtpHeaderExtension(
978 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
979 capabilities.header_extensions.push_back(
980 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
981 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
stefanba4c0e42016-02-04 04:12:24 -0800982 if (webrtc::field_trial::FindFullName("WebRTC-Audio-SendSideBwe") ==
983 "Enabled") {
984 capabilities.header_extensions.push_back(RtpHeaderExtension(
985 kRtpTransportSequenceNumberHeaderExtension,
986 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
987 }
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100988 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989}
990
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800992 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993 return voe_wrapper_->error();
994}
995
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
997 int length) {
solenberg566ef242015-11-06 15:34:49 -0800998 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000999 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001001 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001003 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001005 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001006 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001007 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001008
solenberg72e29d22016-03-08 06:35:16 -08001009 // Skip past boilerplate prefix text.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 if (length < 72) {
1011 std::string msg(trace, length);
1012 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1013 LOG_V(sev) << msg;
1014 } else {
1015 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +02001016 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 }
1018}
1019
solenberg63b34542015-09-29 06:06:31 -07001020void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001021 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1022 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 channels_.push_back(channel);
1024}
1025
solenberg63b34542015-09-29 06:06:31 -07001026void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -08001027 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -07001028 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -08001029 RTC_DCHECK(it != channels_.end());
1030 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031}
1032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033// Adjusts the default AGC target level by the specified delta.
1034// NB: If we start messing with other config fields, we'll want
1035// to save the current webrtc::AgcConfig as well.
1036bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -08001037 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 webrtc::AgcConfig config = default_agc_config_;
1039 config.targetLeveldBOv -= delta;
1040
1041 LOG(LS_INFO) << "Adjusting AGC level from default -"
1042 << default_agc_config_.targetLeveldBOv << "dB to -"
1043 << config.targetLeveldBOv << "dB";
1044
1045 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1046 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1047 return false;
1048 }
1049 return true;
1050}
1051
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001052bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
solenberg566ef242015-11-06 15:34:49 -08001053 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054 if (initialized_) {
1055 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1056 return false;
1057 }
1058 if (adm_) {
1059 adm_->Release();
1060 adm_ = NULL;
1061 }
1062 if (adm) {
1063 adm_ = adm;
1064 adm_->AddRef();
1065 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 return true;
1067}
1068
ivocd66b44d2016-01-15 03:06:36 -08001069bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file,
1070 int64_t max_size_bytes) {
solenberg566ef242015-11-06 15:34:49 -08001071 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001072 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001073 if (!aec_dump_file_stream) {
1074 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001075 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001076 LOG(LS_WARNING) << "Could not close file.";
1077 return false;
1078 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001079 StopAecDump();
ivocd66b44d2016-01-15 03:06:36 -08001080 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1081 aec_dump_file_stream, max_size_bytes) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001082 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001083 LOG_RTCERR0(StartDebugRecording);
1084 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001085 return false;
1086 }
1087 is_dumping_aec_ = true;
1088 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001089}
1090
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001092 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 if (!is_dumping_aec_) {
1094 // Start dumping AEC when we are not dumping.
ivocd66b44d2016-01-15 03:06:36 -08001095 if (voe_wrapper_->base()->audio_processing()->StartDebugRecording(
1096 filename.c_str(), -1) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001097 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 } else {
1099 is_dumping_aec_ = true;
1100 }
1101 }
1102}
1103
1104void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001105 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 if (is_dumping_aec_) {
1107 // Stop dumping AEC when we are dumping.
ivocd66b44d2016-01-15 03:06:36 -08001108 if (voe_wrapper_->base()->audio_processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 webrtc::AudioProcessing::kNoError) {
1110 LOG_RTCERR0(StopDebugRecording);
1111 }
1112 is_dumping_aec_ = false;
1113 }
1114}
1115
ivoc112a3d82015-10-16 02:22:18 -07001116bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001117 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001118 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1119 if (event_log) {
1120 return event_log->StartLogging(file);
1121 }
1122 LOG_RTCERR0(StartRtcEventLog);
1123 return false;
ivoc112a3d82015-10-16 02:22:18 -07001124}
1125
1126void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001127 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc20834ca2016-02-04 06:33:37 -08001128 webrtc::RtcEventLog* event_log = voe_wrapper_->codec()->GetEventLog();
1129 if (event_log) {
1130 event_log->StopLogging();
1131 return;
1132 }
1133 LOG_RTCERR0(StopRtcEventLog);
ivoc112a3d82015-10-16 02:22:18 -07001134}
1135
solenberg0a617e22015-10-20 15:49:38 -07001136int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001137 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001138 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001139}
1140
solenbergc96df772015-10-21 13:01:53 -07001141class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001142 : public AudioSource::Sink {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001143 public:
solenbergc96df772015-10-21 13:01:53 -07001144 WebRtcAudioSendStream(int ch, webrtc::AudioTransport* voe_audio_transport,
solenberg3a941542015-11-16 07:34:50 -08001145 uint32_t ssrc, const std::string& c_name,
1146 const std::vector<webrtc::RtpExtension>& extensions,
1147 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001148 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001149 call_(call),
1150 config_(nullptr) {
solenberg85a04962015-10-27 03:35:21 -07001151 RTC_DCHECK_GE(ch, 0);
1152 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1153 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001154 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001155 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001156 config_.rtp.ssrc = ssrc;
1157 config_.rtp.c_name = c_name;
1158 config_.voe_channel_id = ch;
1159 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001160 }
solenberg3a941542015-11-16 07:34:50 -08001161
solenbergc96df772015-10-21 13:01:53 -07001162 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001163 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001164 ClearSource();
solenbergc96df772015-10-21 13:01:53 -07001165 call_->DestroyAudioSendStream(stream_);
1166 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001167
solenberg3a941542015-11-16 07:34:50 -08001168 void RecreateAudioSendStream(
1169 const std::vector<webrtc::RtpExtension>& extensions) {
1170 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1171 if (stream_) {
1172 call_->DestroyAudioSendStream(stream_);
1173 stream_ = nullptr;
1174 }
1175 config_.rtp.extensions = extensions;
1176 RTC_DCHECK(!stream_);
1177 stream_ = call_->CreateAudioSendStream(config_);
1178 RTC_CHECK(stream_);
1179 }
1180
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001181 bool SendTelephoneEvent(int payload_type, uint8_t event,
1182 uint32_t duration_ms) {
1183 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1184 RTC_DCHECK(stream_);
1185 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1186 }
1187
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001188 void SetSend(bool send) {
1189 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1190 send_ = send;
1191 UpdateSendState();
1192 }
1193
solenberg3a941542015-11-16 07:34:50 -08001194 webrtc::AudioSendStream::Stats GetStats() const {
1195 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1196 RTC_DCHECK(stream_);
1197 return stream_->GetStats();
1198 }
1199
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001200 // Starts the sending by setting ourselves as a sink to the AudioSource to
1201 // get data callbacks.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001202 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001203 // TODO(xians): Make sure Start() is called only once.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001204 void SetSource(AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001205 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001206 RTC_DCHECK(source);
1207 if (source_) {
1208 RTC_DCHECK(source_ == source);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001209 return;
1210 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001211 source->SetSink(this);
1212 source_ = source;
1213 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001214 }
1215
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001216 // Stops sending by setting the sink of the AudioSource to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001217 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001218 // This method is called on the libjingle worker thread.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001219 void ClearSource() {
solenberg566ef242015-11-06 15:34:49 -08001220 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001221 if (source_) {
1222 source_->SetSink(nullptr);
1223 source_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001224 }
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001225 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001226 }
1227
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001228 // AudioSource::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001229 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001230 void OnData(const void* audio_data,
1231 int bits_per_sample,
1232 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001233 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001234 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001235 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001236 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001237 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001238 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001239 audio_data,
1240 bits_per_sample,
1241 sample_rate,
1242 number_of_channels,
1243 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001244 }
1245
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001246 // Callback from the |source_| when it is going away. In case Start() has
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001247 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001248 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001249 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001250 // Set |source_| to nullptr to make sure no more callback will get into
1251 // the source.
1252 source_ = nullptr;
1253 UpdateSendState();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001254 }
1255
1256 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001257 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001258 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001259 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001260 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001261
1262 private:
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001263 void UpdateSendState() {
1264 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1265 RTC_DCHECK(stream_);
1266 if (send_ && source_ != nullptr) {
1267 stream_->Start();
1268 } else { // !send || source_ = nullptr
1269 stream_->Stop();
1270 }
1271 }
1272
solenberg566ef242015-11-06 15:34:49 -08001273 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001274 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001275 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1276 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001277 webrtc::AudioSendStream::Config config_;
1278 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1279 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001280 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001281
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001282 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001283 // PeerConnection will make sure invalidating the pointer before the object
1284 // goes away.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001285 AudioSource* source_ = nullptr;
1286 bool send_ = false;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001287
solenbergc96df772015-10-21 13:01:53 -07001288 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1289};
1290
1291class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1292 public:
stefanba4c0e42016-02-04 04:12:24 -08001293 WebRtcAudioReceiveStream(int ch,
1294 uint32_t remote_ssrc,
1295 uint32_t local_ssrc,
1296 bool use_transport_cc,
1297 const std::string& sync_group,
solenberg7add0582015-11-20 09:59:34 -08001298 const std::vector<webrtc::RtpExtension>& extensions,
1299 webrtc::Call* call)
stefanba4c0e42016-02-04 04:12:24 -08001300 : call_(call), config_() {
solenberg7add0582015-11-20 09:59:34 -08001301 RTC_DCHECK_GE(ch, 0);
1302 RTC_DCHECK(call);
1303 config_.rtp.remote_ssrc = remote_ssrc;
1304 config_.rtp.local_ssrc = local_ssrc;
1305 config_.voe_channel_id = ch;
1306 config_.sync_group = sync_group;
stefanba4c0e42016-02-04 04:12:24 -08001307 RecreateAudioReceiveStream(use_transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001308 }
solenbergc96df772015-10-21 13:01:53 -07001309
solenberg7add0582015-11-20 09:59:34 -08001310 ~WebRtcAudioReceiveStream() {
1311 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1312 call_->DestroyAudioReceiveStream(stream_);
1313 }
1314
1315 void RecreateAudioReceiveStream(
1316 const std::vector<webrtc::RtpExtension>& extensions) {
1317 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001318 RecreateAudioReceiveStream(config_.rtp.transport_cc, extensions);
solenberg7add0582015-11-20 09:59:34 -08001319 }
stefanba4c0e42016-02-04 04:12:24 -08001320 void RecreateAudioReceiveStream(bool use_transport_cc) {
solenberg7add0582015-11-20 09:59:34 -08001321 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
stefanba4c0e42016-02-04 04:12:24 -08001322 RecreateAudioReceiveStream(use_transport_cc, config_.rtp.extensions);
solenberg7add0582015-11-20 09:59:34 -08001323 }
1324
1325 webrtc::AudioReceiveStream::Stats GetStats() const {
1326 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1327 RTC_DCHECK(stream_);
1328 return stream_->GetStats();
1329 }
1330
1331 int channel() const {
1332 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1333 return config_.voe_channel_id;
1334 }
solenbergc96df772015-10-21 13:01:53 -07001335
kwiberg686a8ef2016-02-26 03:00:35 -08001336 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001337 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kwiberg686a8ef2016-02-26 03:00:35 -08001338 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001339 }
1340
solenbergc96df772015-10-21 13:01:53 -07001341 private:
stefanba4c0e42016-02-04 04:12:24 -08001342 void RecreateAudioReceiveStream(
1343 bool use_transport_cc,
solenberg7add0582015-11-20 09:59:34 -08001344 const std::vector<webrtc::RtpExtension>& extensions) {
1345 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1346 if (stream_) {
1347 call_->DestroyAudioReceiveStream(stream_);
1348 stream_ = nullptr;
1349 }
1350 config_.rtp.extensions = extensions;
stefanba4c0e42016-02-04 04:12:24 -08001351 config_.rtp.transport_cc = use_transport_cc;
solenberg7add0582015-11-20 09:59:34 -08001352 RTC_DCHECK(!stream_);
1353 stream_ = call_->CreateAudioReceiveStream(config_);
1354 RTC_CHECK(stream_);
1355 }
1356
1357 rtc::ThreadChecker worker_thread_checker_;
1358 webrtc::Call* call_ = nullptr;
1359 webrtc::AudioReceiveStream::Config config_;
1360 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1361 // configuration changes.
1362 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001363
1364 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001365};
1366
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001367WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
nisse51542be2016-02-12 02:27:06 -08001368 const MediaConfig& config,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001369 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001370 webrtc::Call* call)
nisse51542be2016-02-12 02:27:06 -08001371 : VoiceMediaChannel(config), engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001372 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001373 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001374 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001375 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376}
1377
1378WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001379 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001380 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001381 // TODO(solenberg): Should be able to delete the streams directly, without
1382 // going through RemoveNnStream(), once stream objects handle
1383 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001384 while (!send_streams_.empty()) {
1385 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001386 }
solenberg7add0582015-11-20 09:59:34 -08001387 while (!recv_streams_.empty()) {
1388 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 }
solenberg0a617e22015-10-20 15:49:38 -07001390 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391}
1392
nisse51542be2016-02-12 02:27:06 -08001393rtc::DiffServCodePoint WebRtcVoiceMediaChannel::PreferredDscp() const {
1394 return kAudioDscpValue;
1395}
1396
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001397bool WebRtcVoiceMediaChannel::SetSendParameters(
1398 const AudioSendParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001399 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
solenberg566ef242015-11-06 15:34:49 -08001400 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001401 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1402 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001403 // TODO(pthatcher): Refactor this to be more clean now that we have
1404 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001405
1406 if (!SetSendCodecs(params.codecs)) {
1407 return false;
1408 }
1409
solenberg7e4e01a2015-12-02 08:05:01 -08001410 if (!ValidateRtpExtensions(params.extensions)) {
1411 return false;
1412 }
1413 std::vector<webrtc::RtpExtension> filtered_extensions =
1414 FilterRtpExtensions(params.extensions,
1415 webrtc::RtpExtension::IsSupportedForAudio, true);
1416 if (send_rtp_extensions_ != filtered_extensions) {
1417 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001418 for (auto& it : send_streams_) {
1419 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1420 }
1421 }
1422
1423 if (!SetMaxSendBandwidth(params.max_bandwidth_bps)) {
1424 return false;
1425 }
1426 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001427}
1428
1429bool WebRtcVoiceMediaChannel::SetRecvParameters(
1430 const AudioRecvParameters& params) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001431 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
solenberg566ef242015-11-06 15:34:49 -08001432 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001433 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1434 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001435 // TODO(pthatcher): Refactor this to be more clean now that we have
1436 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001437
1438 if (!SetRecvCodecs(params.codecs)) {
1439 return false;
1440 }
1441
solenberg7e4e01a2015-12-02 08:05:01 -08001442 if (!ValidateRtpExtensions(params.extensions)) {
1443 return false;
1444 }
1445 std::vector<webrtc::RtpExtension> filtered_extensions =
1446 FilterRtpExtensions(params.extensions,
1447 webrtc::RtpExtension::IsSupportedForAudio, false);
1448 if (recv_rtp_extensions_ != filtered_extensions) {
1449 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001450 for (auto& it : recv_streams_) {
1451 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1452 }
1453 }
solenberg7add0582015-11-20 09:59:34 -08001454 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001455}
1456
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001458 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 LOG(LS_INFO) << "Setting voice channel options: "
1460 << options.ToString();
1461
1462 // We retain all of the existing options, and apply the given ones
1463 // on top. This means there is no way to "clear" options such that
1464 // they go back to the engine default.
1465 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001466 if (!engine()->ApplyOptions(options_)) {
1467 LOG(LS_WARNING) <<
1468 "Failed to apply engine options during channel SetOptions.";
1469 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 LOG(LS_INFO) << "Set voice channel options. Current options: "
1472 << options_.ToString();
1473 return true;
1474}
1475
1476bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1477 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001478 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001479
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001481 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001482
1483 if (!VerifyUniquePayloadTypes(codecs)) {
1484 LOG(LS_ERROR) << "Codec payload types overlap.";
1485 return false;
1486 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487
1488 std::vector<AudioCodec> new_codecs;
1489 // Find all new codecs. We allow adding new codecs but don't allow changing
1490 // the payload type of codecs that is already configured since we might
1491 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001492 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001494 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1495 if (old_codec.id != codec.id) {
1496 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497 return false;
1498 }
1499 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001500 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501 }
1502 }
1503 if (new_codecs.empty()) {
1504 // There are no new codecs to configure. Already configured codecs are
1505 // never removed.
1506 return true;
1507 }
1508
1509 if (playout_) {
1510 // Receive codecs can not be changed while playing. So we temporarily
1511 // pause playout.
1512 PausePlayout();
1513 }
1514
solenberg26c8c912015-11-27 04:00:25 -08001515 bool result = true;
1516 for (const AudioCodec& codec : new_codecs) {
solenberg72e29d22016-03-08 06:35:16 -08001517 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08001518 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1519 LOG(LS_INFO) << ToString(codec);
1520 voe_codec.pltype = codec.id;
1521 for (const auto& ch : recv_streams_) {
1522 if (engine()->voe()->codec()->SetRecPayloadType(
1523 ch.second->channel(), voe_codec) == -1) {
1524 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1525 ToString(voe_codec));
1526 result = false;
1527 }
1528 }
1529 } else {
1530 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1531 result = false;
1532 break;
1533 }
1534 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001535 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536 recv_codecs_ = codecs;
1537 }
1538
1539 if (desired_playout_ && !playout_) {
1540 ResumePlayout();
1541 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001542 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001543}
1544
solenberg72e29d22016-03-08 06:35:16 -08001545// Utility function called from SetSendParameters() to extract current send
1546// codec settings from the given list of codecs (originally from SDP). Both send
1547// and receive streams may be reconfigured based on the new settings.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001548bool WebRtcVoiceMediaChannel::SetSendCodecs(
1549 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001550 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001551 // TODO(solenberg): Validate input - that payload types don't overlap, are
1552 // within range, filter out codecs we don't support,
1553 // redundant codecs etc.
solenbergd97ec302015-10-07 01:40:33 -07001554
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001555 // Find the DTMF telephone event "codec" payload type.
1556 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001557 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001558 if (IsCodec(codec, kDtmfCodecName)) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001559 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1560 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001561 }
1562 }
1563
solenberg72e29d22016-03-08 06:35:16 -08001564 // Scan through the list to figure out the codec to use for sending, along
1565 // with the proper configuration for VAD, CNG, RED, NACK and Opus-specific
1566 // parameters.
1567 {
1568 SendCodecSpec send_codec_spec;
1569 send_codec_spec.nack_enabled = send_codec_spec_.nack_enabled;
1570
1571 // Find send codec (the first non-telephone-event/CN codec).
1572 const AudioCodec* codec = WebRtcVoiceCodecs::GetPreferredCodec(
1573 codecs, &send_codec_spec.codec_inst, &send_codec_spec.red_payload_type);
1574 if (!codec) {
1575 LOG(LS_WARNING) << "Received empty list of codecs.";
1576 return false;
1577 }
1578
1579 send_codec_spec.transport_cc_enabled = HasTransportCc(*codec);
1580
1581 // This condition is apparently here because Opus does not support RED and
1582 // FEC simultaneously. However, DTX and max playback rate shouldn't have
1583 // such limitations.
1584 // TODO(solenberg): Refactor this logic once we create AudioEncoders here.
1585 if (send_codec_spec.red_payload_type == -1) {
1586 send_codec_spec.nack_enabled = HasNack(*codec);
1587 // For Opus as the send codec, we are to determine inband FEC, maximum
1588 // playback rate, and opus internal dtx.
1589 if (IsCodec(*codec, kOpusCodecName)) {
1590 GetOpusConfig(*codec, &send_codec_spec.codec_inst,
1591 &send_codec_spec.enable_codec_fec,
1592 &send_codec_spec.opus_max_playback_rate,
1593 &send_codec_spec.enable_opus_dtx);
1594 }
1595
1596 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1597 int ptime_ms = 0;
1598 if (codec->GetParam(kCodecParamPTime, &ptime_ms)) {
1599 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(
1600 &send_codec_spec.codec_inst, ptime_ms)) {
1601 LOG(LS_WARNING) << "Failed to set packet size for codec "
1602 << send_codec_spec.codec_inst.plname;
1603 return false;
1604 }
1605 }
1606 }
1607
1608 // Loop through the codecs list again to find the CN codec.
1609 // TODO(solenberg): Break out into a separate function?
1610 for (const AudioCodec& codec : codecs) {
1611 // Ignore codecs we don't know about. The negotiation step should prevent
1612 // this, but double-check to be sure.
1613 webrtc::CodecInst voe_codec = {0};
1614 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1615 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1616 continue;
1617 }
1618
1619 if (IsCodec(codec, kCnCodecName)) {
1620 // Turn voice activity detection/comfort noise on if supported.
1621 // Set the wideband CN payload type appropriately.
1622 // (narrowband always uses the static payload type 13).
1623 int cng_plfreq = -1;
1624 switch (codec.clockrate) {
1625 case 8000:
1626 case 16000:
1627 case 32000:
1628 cng_plfreq = codec.clockrate;
1629 break;
1630 default:
1631 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
1632 << " not supported.";
1633 continue;
1634 }
1635 send_codec_spec.cng_payload_type = codec.id;
1636 send_codec_spec.cng_plfreq = cng_plfreq;
1637 break;
1638 }
1639 }
1640
1641 // Latch in the new state.
1642 send_codec_spec_ = std::move(send_codec_spec);
1643 }
1644
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001645 // Cache the codecs in order to configure the channel created later.
solenbergc96df772015-10-21 13:01:53 -07001646 for (const auto& ch : send_streams_) {
solenberg72e29d22016-03-08 06:35:16 -08001647 if (!SetSendCodecs(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001648 return false;
1649 }
1650 }
1651
solenberg72e29d22016-03-08 06:35:16 -08001652 // Set nack status on receive channels.
1653 if (!send_streams_.empty()) {
1654 for (const auto& kv : recv_streams_) {
1655 SetNack(kv.second->channel(), send_codec_spec_.nack_enabled);
1656 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001657 }
solenberg0a617e22015-10-20 15:49:38 -07001658
stefanba4c0e42016-02-04 04:12:24 -08001659 // Check if the transport cc feedback has changed on the preferred send codec,
1660 // and in that case reconfigure all receive streams.
solenberg72e29d22016-03-08 06:35:16 -08001661 if (recv_transport_cc_enabled_ != send_codec_spec_.transport_cc_enabled) {
1662 LOG(LS_INFO) << "Recreate all the receive streams because the send "
1663 "codec has changed.";
1664 recv_transport_cc_enabled_ = send_codec_spec_.transport_cc_enabled;
1665 for (auto& kv : recv_streams_) {
1666 kv.second->RecreateAudioReceiveStream(recv_transport_cc_enabled_);
1667 }
1668 }
1669
1670 return true;
1671}
1672
1673// Apply current codec settings to a single voe::Channel used for sending.
1674bool WebRtcVoiceMediaChannel::SetSendCodecs(int channel) {
1675 // Disable VAD, FEC, and RED unless we know the other side wants them.
1676 engine()->voe()->codec()->SetVADStatus(channel, false);
1677 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1678 engine()->voe()->rtp()->SetREDStatus(channel, false);
1679 engine()->voe()->codec()->SetFECStatus(channel, false);
1680
1681 if (send_codec_spec_.red_payload_type != -1) {
1682 // Enable redundant encoding of the specified codec. Treat any
1683 // failure as a fatal internal error.
1684 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1685 if (engine()->voe()->rtp()->SetREDStatus(channel, true,
1686 send_codec_spec_.red_payload_type) == -1) {
1687 LOG_RTCERR3(SetREDStatus, channel, true,
1688 send_codec_spec_.red_payload_type);
1689 return false;
1690 }
1691 }
1692
1693 SetNack(channel, send_codec_spec_.nack_enabled);
1694
1695 // Set the codec immediately, since SetVADStatus() depends on whether
1696 // the current codec is mono or stereo.
1697 if (!SetSendCodec(channel, send_codec_spec_.codec_inst)) {
1698 return false;
1699 }
1700
1701 // FEC should be enabled after SetSendCodec.
1702 if (send_codec_spec_.enable_codec_fec) {
1703 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1704 << channel;
1705 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1706 // Enable codec internal FEC. Treat any failure as fatal internal error.
1707 LOG_RTCERR2(SetFECStatus, channel, true);
1708 return false;
1709 }
1710 }
1711
1712 if (IsCodec(send_codec_spec_.codec_inst, kOpusCodecName)) {
1713 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1714 // send codec has to be Opus.
1715
1716 // Set Opus internal DTX.
1717 LOG(LS_INFO) << "Attempt to "
1718 << (send_codec_spec_.enable_opus_dtx ? "enable" : "disable")
1719 << " Opus DTX on channel "
1720 << channel;
1721 if (engine()->voe()->codec()->SetOpusDtx(channel,
1722 send_codec_spec_.enable_opus_dtx)) {
1723 LOG_RTCERR2(SetOpusDtx, channel, send_codec_spec_.enable_opus_dtx);
1724 return false;
1725 }
1726
1727 // If opus_max_playback_rate <= 0, the default maximum playback rate
1728 // (48 kHz) will be used.
1729 if (send_codec_spec_.opus_max_playback_rate > 0) {
1730 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1731 << send_codec_spec_.opus_max_playback_rate
1732 << " Hz on channel "
1733 << channel;
1734 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1735 channel, send_codec_spec_.opus_max_playback_rate) == -1) {
1736 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel,
1737 send_codec_spec_.opus_max_playback_rate);
1738 return false;
stefanba4c0e42016-02-04 04:12:24 -08001739 }
1740 }
1741 }
1742
solenberg72e29d22016-03-08 06:35:16 -08001743 if (send_bitrate_setting_) {
1744 SetSendBitrateInternal(send_bitrate_bps_);
1745 }
1746
1747 // Set the CN payloadtype and the VAD status.
1748 if (send_codec_spec_.cng_payload_type != -1) {
1749 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1750 if (send_codec_spec_.cng_plfreq != 8000) {
1751 webrtc::PayloadFrequencies cn_freq;
1752 switch (send_codec_spec_.cng_plfreq) {
1753 case 16000:
1754 cn_freq = webrtc::kFreq16000Hz;
1755 break;
1756 case 32000:
1757 cn_freq = webrtc::kFreq32000Hz;
1758 break;
1759 default:
1760 RTC_NOTREACHED();
1761 return false;
1762 }
1763 if (engine()->voe()->codec()->SetSendCNPayloadType(
1764 channel, send_codec_spec_.cng_payload_type, cn_freq) == -1) {
1765 LOG_RTCERR3(SetSendCNPayloadType, channel,
1766 send_codec_spec_.cng_payload_type, cn_freq);
1767 // TODO(ajm): This failure condition will be removed from VoE.
1768 // Restore the return here when we update to a new enough webrtc.
1769 //
1770 // Not returning false because the SetSendCNPayloadType will fail if
1771 // the channel is already sending.
1772 // This can happen if the remote description is applied twice, for
1773 // example in the case of ROAP on top of JSEP, where both side will
1774 // send the offer.
1775 }
1776 }
1777
1778 // Only turn on VAD if we have a CN payload type that matches the
1779 // clockrate for the codec we are going to use.
1780 if (send_codec_spec_.cng_plfreq == send_codec_spec_.codec_inst.plfreq &&
1781 send_codec_spec_.codec_inst.channels == 1) {
1782 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1783 // interaction between VAD and Opus FEC.
1784 LOG(LS_INFO) << "Enabling VAD";
1785 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1786 LOG_RTCERR2(SetVADStatus, channel, true);
1787 return false;
1788 }
1789 }
1790 }
solenberg0a617e22015-10-20 15:49:38 -07001791 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001792}
1793
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001794void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001796 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1798 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001799 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1801 }
1802}
1803
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001805 int channel, const webrtc::CodecInst& send_codec) {
1806 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1807 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1808
solenberg72e29d22016-03-08 06:35:16 -08001809 webrtc::CodecInst current_codec = {0};
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001810 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1811 (send_codec == current_codec)) {
1812 // Codec is already configured, we can return without setting it again.
1813 return true;
1814 }
1815
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001816 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1817 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818 return false;
1819 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return true;
1821}
1822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1824 desired_playout_ = playout;
1825 return ChangePlayout(desired_playout_);
1826}
1827
1828bool WebRtcVoiceMediaChannel::PausePlayout() {
1829 return ChangePlayout(false);
1830}
1831
1832bool WebRtcVoiceMediaChannel::ResumePlayout() {
1833 return ChangePlayout(desired_playout_);
1834}
1835
1836bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001837 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::ChangePlayout");
solenberg566ef242015-11-06 15:34:49 -08001838 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 if (playout_ == playout) {
1840 return true;
1841 }
1842
solenberg7add0582015-11-20 09:59:34 -08001843 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001844 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001845 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001846 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001847 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 }
1849 }
solenberg1ac56142015-10-13 03:58:19 -07001850 playout_ = playout;
1851 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001852}
1853
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001854void WebRtcVoiceMediaChannel::SetSend(bool send) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001855 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 if (send_ == send) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001857 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 }
1859
solenberg246b8172015-12-08 09:50:23 -08001860 // Apply channel specific options when channel is enabled for sending.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001861 if (send) {
solenberg63b34542015-09-29 06:06:31 -07001862 engine()->ApplyOptions(options_);
1863 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001865 // Change the settings on each send channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001866 for (auto& kv : send_streams_) {
1867 kv.second->SetSend(send);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001868 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001869
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 send_ = send;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871}
1872
Peter Boström0c4e06b2015-10-07 12:23:21 +02001873bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1874 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001875 const AudioOptions* options,
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001876 AudioSource* source) {
solenberg566ef242015-11-06 15:34:49 -08001877 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001878 // TODO(solenberg): The state change should be fully rolled back if any one of
1879 // these calls fail.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001880 if (!SetLocalSource(ssrc, source)) {
solenberg1dd98f32015-09-10 01:57:14 -07001881 return false;
1882 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001883 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001884 return false;
1885 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001886 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001887 return SetOptions(*options);
1888 }
1889 return true;
1890}
1891
solenberg0a617e22015-10-20 15:49:38 -07001892int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1893 int id = engine()->CreateVoEChannel();
1894 if (id == -1) {
1895 LOG_RTCERR0(CreateVoEChannel);
1896 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001897 }
solenberg0a617e22015-10-20 15:49:38 -07001898 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1899 LOG_RTCERR2(RegisterExternalTransport, id, this);
1900 engine()->voe()->base()->DeleteChannel(id);
1901 return -1;
1902 }
1903 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001904}
1905
solenberg7add0582015-11-20 09:59:34 -08001906bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001907 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1908 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1909 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001910 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1911 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 return false;
1913 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001914 return true;
1915}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001916
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001917bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001918 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
solenberg566ef242015-11-06 15:34:49 -08001919 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001920 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1921
1922 uint32_t ssrc = sp.first_ssrc();
1923 RTC_DCHECK(0 != ssrc);
1924
1925 if (GetSendChannelId(ssrc) != -1) {
1926 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001927 return false;
1928 }
1929
solenberg0a617e22015-10-20 15:49:38 -07001930 // Create a new channel for sending audio data.
1931 int channel = CreateVoEChannel();
1932 if (channel == -1) {
1933 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001934 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001935
solenbergc96df772015-10-21 13:01:53 -07001936 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001937 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001938 webrtc::AudioTransport* audio_transport =
1939 engine()->voe()->base()->audio_transport();
solenberg3a941542015-11-16 07:34:50 -08001940 send_streams_.insert(std::make_pair(ssrc, new WebRtcAudioSendStream(
1941 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001942
solenberg0a617e22015-10-20 15:49:38 -07001943 // Set the current codecs to be used for the new channel. We need to do this
1944 // after adding the channel to send_channels_, because of how max bitrate is
1945 // currently being configured by SetSendCodec().
solenberg72e29d22016-03-08 06:35:16 -08001946 if (HasSendCodec() && !SetSendCodecs(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001947 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001948 return false;
1949 }
1950
1951 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001952 // the first send channel make sure that all the receive channels are updated
1953 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001954 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001955 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001956 for (const auto& stream : recv_streams_) {
1957 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001958 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001959 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001960 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001961 }
solenberg0a617e22015-10-20 15:49:38 -07001962 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1963 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1964 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001965 }
1966 }
1967
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001968 send_streams_[ssrc]->SetSend(send_);
1969 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001970}
1971
Peter Boström0c4e06b2015-10-07 12:23:21 +02001972bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08001973 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
solenberg566ef242015-11-06 15:34:49 -08001974 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001975 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1976
solenbergc96df772015-10-21 13:01:53 -07001977 auto it = send_streams_.find(ssrc);
1978 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001979 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1980 << " which doesn't exist.";
1981 return false;
1982 }
1983
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001984 it->second->SetSend(false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001985
solenberg7add0582015-11-20 09:59:34 -08001986 // Clean up and delete the send stream+channel.
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001987 int channel = it->second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001988 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1989 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001990 delete it->second;
1991 send_streams_.erase(it);
1992 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001993 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001994 }
solenbergc96df772015-10-21 13:01:53 -07001995 if (send_streams_.empty()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08001996 SetSend(false);
solenberg0a617e22015-10-20 15:49:38 -07001997 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 return true;
1999}
2000
2001bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002002 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002003 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002004 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
2005
solenberg0b675462015-10-09 01:37:09 -07002006 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00002007 return false;
2008 }
2009
solenberg7add0582015-11-20 09:59:34 -08002010 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07002011 if (ssrc == 0) {
2012 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
2013 return false;
2014 }
2015
solenberg1ac56142015-10-13 03:58:19 -07002016 // Remove the default receive stream if one had been created with this ssrc;
2017 // we'll recreate it then.
2018 if (IsDefaultRecvStream(ssrc)) {
2019 RemoveRecvStream(ssrc);
2020 }
solenberg0b675462015-10-09 01:37:09 -07002021
solenberg7add0582015-11-20 09:59:34 -08002022 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002023 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024 return false;
2025 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002026
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08002028 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 return false;
2031 }
Minyue2013aec2015-05-13 14:14:42 +02002032
solenberg1ac56142015-10-13 03:58:19 -07002033 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08002034 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
2035 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
2036 voe_codec.pltype = -1;
2037 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
2038 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2039 DeleteVoEChannel(channel);
2040 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041 }
2042 }
2043
solenberg1ac56142015-10-13 03:58:19 -07002044 // Only enable those configured for this channel.
2045 for (const auto& codec : recv_codecs_) {
solenberg72e29d22016-03-08 06:35:16 -08002046 webrtc::CodecInst voe_codec = {0};
solenberg26c8c912015-11-27 04:00:25 -08002047 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07002048 voe_codec.pltype = codec.id;
2049 if (engine()->voe()->codec()->SetRecPayloadType(
2050 channel, voe_codec) == -1) {
2051 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08002052 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07002053 return false;
2054 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002055 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 }
solenberg8fb30c32015-10-13 03:06:58 -07002057
solenberg7add0582015-11-20 09:59:34 -08002058 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
2059 if (send_channel != -1) {
2060 // Associate receive channel with first send channel (so the receive channel
2061 // can obtain RTT from the send channel)
2062 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2063 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2064 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002065 }
2066
stefanba4c0e42016-02-04 04:12:24 -08002067 recv_streams_.insert(std::make_pair(
2068 ssrc, new WebRtcAudioReceiveStream(channel, ssrc, receiver_reports_ssrc_,
solenberg72e29d22016-03-08 06:35:16 -08002069 recv_transport_cc_enabled_,
2070 sp.sync_label, recv_rtp_extensions_,
2071 call_)));
solenberg7add0582015-11-20 09:59:34 -08002072
solenberg72e29d22016-03-08 06:35:16 -08002073 SetNack(channel, send_codec_spec_.nack_enabled);
solenberg1ac56142015-10-13 03:58:19 -07002074 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002075
solenberg1ac56142015-10-13 03:58:19 -07002076 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077}
2078
Peter Boström0c4e06b2015-10-07 12:23:21 +02002079bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002080 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
solenberg566ef242015-11-06 15:34:49 -08002081 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002082 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2083
solenberg7add0582015-11-20 09:59:34 -08002084 const auto it = recv_streams_.find(ssrc);
2085 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002086 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2087 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002088 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002089 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090
solenberg1ac56142015-10-13 03:58:19 -07002091 // Deregister default channel, if that's the one being destroyed.
2092 if (IsDefaultRecvStream(ssrc)) {
2093 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002095
solenberg7add0582015-11-20 09:59:34 -08002096 const int channel = it->second->channel();
2097
2098 // Clean up and delete the receive stream+channel.
2099 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002100 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002101 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002102 delete it->second;
2103 recv_streams_.erase(it);
2104 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105}
2106
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002107bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
2108 AudioSource* source) {
solenbergc96df772015-10-21 13:01:53 -07002109 auto it = send_streams_.find(ssrc);
2110 if (it == send_streams_.end()) {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002111 if (source) {
2112 // Return an error if trying to set a valid source with an invalid ssrc.
2113 LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002114 return false;
2115 }
2116
2117 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002118 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002119 }
2120
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002121 if (source) {
2122 it->second->SetSource(source);
solenberg1ac56142015-10-13 03:58:19 -07002123 } else {
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002124 it->second->ClearSource();
solenberg1ac56142015-10-13 03:58:19 -07002125 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002127 return true;
2128}
2129
2130bool WebRtcVoiceMediaChannel::GetActiveStreams(
2131 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002132 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002134 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002135 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002137 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 }
2139 }
2140 return true;
2141}
2142
2143int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002144 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002145 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002146 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002147 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 }
2149 return highest;
2150}
2151
2152int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2153 int ret;
2154 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2155 // In case of error, log the info and continue
2156 LOG_RTCERR0(TimeSinceLastTyping);
2157 ret = -1;
2158 } else {
2159 ret *= 1000; // We return ms, webrtc returns seconds.
2160 }
2161 return ret;
2162}
2163
2164void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2165 int cost_per_typing, int reporting_threshold, int penalty_decay,
2166 int type_event_delay) {
2167 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2168 time_window, cost_per_typing,
2169 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2170 // In case of error, log the info and continue
2171 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2172 cost_per_typing, reporting_threshold, penalty_decay,
2173 type_event_delay);
2174 }
2175}
2176
solenberg4bac9c52015-10-09 02:32:53 -07002177bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002178 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002179 if (ssrc == 0) {
2180 default_recv_volume_ = volume;
2181 if (default_recv_ssrc_ == -1) {
2182 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 }
solenberg1ac56142015-10-13 03:58:19 -07002184 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2185 }
2186 int ch_id = GetReceiveChannelId(ssrc);
2187 if (ch_id < 0) {
2188 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2189 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002190 }
2191
solenberg1ac56142015-10-13 03:58:19 -07002192 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2193 volume)) {
2194 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2195 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196 }
solenberg1ac56142015-10-13 03:58:19 -07002197 LOG(LS_INFO) << "SetOutputVolume to " << volume
2198 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002199 return true;
2200}
2201
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002203 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002204}
2205
solenberg1d63dd02015-12-02 12:35:09 -08002206bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2207 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002208 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002209 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2210 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 return false;
2212 }
2213
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002214 // Figure out which WebRtcAudioSendStream to send the event on.
2215 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2216 if (it == send_streams_.end()) {
2217 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002218 return false;
2219 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002220 if (event < kMinTelephoneEventCode ||
2221 event > kMaxTelephoneEventCode) {
2222 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002223 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002225 if (duration < kMinTelephoneEventDuration ||
2226 duration > kMaxTelephoneEventDuration) {
2227 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2228 return false;
2229 }
2230 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231}
2232
wu@webrtc.orga9890802013-12-13 00:21:03 +00002233void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002234 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002235 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002236
solenberg1ac56142015-10-13 03:58:19 -07002237 uint32_t ssrc = 0;
2238 if (!GetRtpSsrc(packet->data(), packet->size(), &ssrc)) {
2239 return;
2240 }
2241
solenberg7e63ef02015-11-20 00:19:43 -08002242 // If we don't have a default channel, and the SSRC is unknown, create a
2243 // default channel.
2244 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002245 StreamParams sp;
2246 sp.ssrcs.push_back(ssrc);
2247 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2248 if (!AddRecvStream(sp)) {
2249 LOG(LS_WARNING) << "Could not create default receive stream.";
2250 return;
2251 }
2252 default_recv_ssrc_ = ssrc;
2253 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
deadbeef884f5852016-01-15 09:20:04 -08002254 if (default_sink_) {
kwiberg686a8ef2016-02-26 03:00:35 -08002255 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002256 new ProxySink(default_sink_.get()));
2257 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2258 }
solenberg1ac56142015-10-13 03:58:19 -07002259 }
2260
2261 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002262 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2263 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002264 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2265 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2266 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2267 webrtc_packet_time);
2268 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002269 // If the SSRC is unknown here, route it to the default channel, if we have
2270 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2271 if (default_recv_ssrc_ == -1) {
2272 return;
2273 } else {
2274 ssrc = default_recv_ssrc_;
2275 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 }
2277
solenberg1ac56142015-10-13 03:58:19 -07002278 // Find the channel to send this packet to. It must exist since webrtc::Call
2279 // was able to demux the packet.
2280 int channel = GetReceiveChannelId(ssrc);
2281 RTC_DCHECK(channel != -1);
2282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002284 engine()->voe()->network()->ReceivedRTPPacket(
solenberg1ac56142015-10-13 03:58:19 -07002285 channel, packet->data(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002286}
2287
wu@webrtc.orga9890802013-12-13 00:21:03 +00002288void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002289 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002290 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002291
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002292 // Forward packet to Call as well.
2293 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2294 packet_time.not_before);
2295 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2296 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2297 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002298
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002299 // Sending channels need all RTCP packets with feedback information.
2300 // Even sender reports can contain attached report blocks.
2301 // Receiving channels need sender reports in order to create
2302 // correct receiver reports.
2303 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002304 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002305 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2306 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 }
2308
solenberg0b675462015-10-09 01:37:09 -07002309 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002310 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002311 uint32_t ssrc = 0;
2312 if (!GetRtcpSsrc(packet->data(), packet->size(), &ssrc)) {
2313 return;
2314 }
2315 int recv_channel_id = GetReceiveChannelId(ssrc);
2316 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002317 engine()->voe()->network()->ReceivedRTCPPacket(
solenberg0b675462015-10-09 01:37:09 -07002318 recv_channel_id, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002319 }
2320 }
2321
2322 // SR may continue RR and any RR entry may correspond to any one of the send
2323 // channels. So all RTCP packets must be forwarded all send channels. VoE
2324 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002325 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002326 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002327 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002328 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329}
2330
Peter Boström0c4e06b2015-10-07 12:23:21 +02002331bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002332 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002333 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002334 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2336 return false;
2337 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002338 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2339 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 return false;
2341 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002342 // We set the AGC to mute state only when all the channels are muted.
2343 // This implementation is not ideal, instead we should signal the AGC when
2344 // the mic channel is muted/unmuted. We can't do it today because there
2345 // is no good way to know which stream is mapping to the mic channel.
2346 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002347 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002348 if (!all_muted) {
2349 break;
2350 }
2351 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002352 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002353 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002354 return false;
2355 }
2356 }
2357
2358 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002359 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002360 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002361 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002362 return true;
2363}
2364
minyue@webrtc.org26236952014-10-29 02:27:08 +00002365// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2366// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002367bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002368 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
minyue@webrtc.org26236952014-10-29 02:27:08 +00002369 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002370}
2371
minyue@webrtc.org26236952014-10-29 02:27:08 +00002372bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2373 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002374
minyue@webrtc.org26236952014-10-29 02:27:08 +00002375 send_bitrate_setting_ = true;
2376 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002377
solenberg72e29d22016-03-08 06:35:16 -08002378 if (!HasSendCodec()) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002379 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002380 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002381 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002382 }
2383
minyue@webrtc.org26236952014-10-29 02:27:08 +00002384 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002385 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2386 // SetMaxSendBandwith(0), the second call removes the previous limit.
2387 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388 return true;
2389
solenberg72e29d22016-03-08 06:35:16 -08002390 webrtc::CodecInst codec = send_codec_spec_.codec_inst;
solenberg26c8c912015-11-27 04:00:25 -08002391 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392
2393 if (is_multi_rate) {
2394 // If codec is multi-rate then just set the bitrate.
2395 codec.rate = bps;
solenbergc96df772015-10-21 13:01:53 -07002396 for (const auto& ch : send_streams_) {
solenberg0a617e22015-10-20 15:49:38 -07002397 if (!SetSendCodec(ch.second->channel(), codec)) {
2398 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2399 << " to bitrate " << bps << " bps.";
2400 return false;
2401 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 }
2403 return true;
2404 } else {
2405 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2406 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2407 // fixed bitrate then ignore.
2408 if (bps < codec.rate) {
2409 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2410 << " to bitrate " << bps << " bps"
2411 << ", requires at least " << codec.rate << " bps.";
2412 return false;
2413 }
2414 return true;
2415 }
2416}
2417
2418bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
Peter Boströmca8b4042016-03-08 14:24:13 -08002419 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
solenberg566ef242015-11-06 15:34:49 -08002420 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002421 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002422
solenberg85a04962015-10-27 03:35:21 -07002423 // Get SSRC and stats for each sender.
2424 RTC_DCHECK(info->senders.size() == 0);
2425 for (const auto& stream : send_streams_) {
2426 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002427 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002428 sinfo.add_ssrc(stats.local_ssrc);
2429 sinfo.bytes_sent = stats.bytes_sent;
2430 sinfo.packets_sent = stats.packets_sent;
2431 sinfo.packets_lost = stats.packets_lost;
2432 sinfo.fraction_lost = stats.fraction_lost;
2433 sinfo.codec_name = stats.codec_name;
2434 sinfo.ext_seqnum = stats.ext_seqnum;
2435 sinfo.jitter_ms = stats.jitter_ms;
2436 sinfo.rtt_ms = stats.rtt_ms;
2437 sinfo.audio_level = stats.audio_level;
2438 sinfo.aec_quality_min = stats.aec_quality_min;
2439 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2440 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2441 sinfo.echo_return_loss = stats.echo_return_loss;
2442 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -08002443 sinfo.typing_noise_detected = (send_ ? stats.typing_noise_detected : false);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002444 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 }
2446
solenberg85a04962015-10-27 03:35:21 -07002447 // Get SSRC and stats for each receiver.
2448 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002449 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002450 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2451 VoiceReceiverInfo rinfo;
2452 rinfo.add_ssrc(stats.remote_ssrc);
2453 rinfo.bytes_rcvd = stats.bytes_rcvd;
2454 rinfo.packets_rcvd = stats.packets_rcvd;
2455 rinfo.packets_lost = stats.packets_lost;
2456 rinfo.fraction_lost = stats.fraction_lost;
2457 rinfo.codec_name = stats.codec_name;
2458 rinfo.ext_seqnum = stats.ext_seqnum;
2459 rinfo.jitter_ms = stats.jitter_ms;
2460 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2461 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2462 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2463 rinfo.audio_level = stats.audio_level;
2464 rinfo.expand_rate = stats.expand_rate;
2465 rinfo.speech_expand_rate = stats.speech_expand_rate;
2466 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2467 rinfo.accelerate_rate = stats.accelerate_rate;
2468 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2469 rinfo.decoding_calls_to_silence_generator =
2470 stats.decoding_calls_to_silence_generator;
2471 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2472 rinfo.decoding_normal = stats.decoding_normal;
2473 rinfo.decoding_plc = stats.decoding_plc;
2474 rinfo.decoding_cng = stats.decoding_cng;
2475 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2476 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2477 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 }
2479
2480 return true;
2481}
2482
Tommif888bb52015-12-12 01:37:01 +01002483void WebRtcVoiceMediaChannel::SetRawAudioSink(
2484 uint32_t ssrc,
kwiberg686a8ef2016-02-26 03:00:35 -08002485 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002486 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef884f5852016-01-15 09:20:04 -08002487 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:" << ssrc
2488 << " " << (sink ? "(ptr)" : "NULL");
2489 if (ssrc == 0) {
2490 if (default_recv_ssrc_ != -1) {
kwiberg686a8ef2016-02-26 03:00:35 -08002491 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
deadbeef884f5852016-01-15 09:20:04 -08002492 sink ? new ProxySink(sink.get()) : nullptr);
2493 SetRawAudioSink(default_recv_ssrc_, std::move(proxy_sink));
2494 }
2495 default_sink_ = std::move(sink);
2496 return;
2497 }
Tommif888bb52015-12-12 01:37:01 +01002498 const auto it = recv_streams_.find(ssrc);
2499 if (it == recv_streams_.end()) {
2500 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2501 return;
2502 }
deadbeef2d110be2016-01-13 12:00:26 -08002503 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002504}
2505
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002506int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002507 unsigned int ulevel = 0;
2508 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002509 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2510}
2511
Peter Boström0c4e06b2015-10-07 12:23:21 +02002512int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002513 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002514 const auto it = recv_streams_.find(ssrc);
2515 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002516 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002517 }
solenberg1ac56142015-10-13 03:58:19 -07002518 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002519}
2520
Peter Boström0c4e06b2015-10-07 12:23:21 +02002521int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002522 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002523 const auto it = send_streams_.find(ssrc);
2524 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002525 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002526 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002527 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528}
2529
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002530bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2531 if (playout) {
2532 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2533 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2534 LOG_RTCERR1(StartPlayout, channel);
2535 return false;
2536 }
2537 } else {
2538 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2539 engine()->voe()->base()->StopPlayout(channel);
2540 }
2541 return true;
2542}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543} // namespace cricket
2544
2545#endif // HAVE_WEBRTC_VOICE