blob: 4285af35497bf3f06913a9773c614a8eb8e8734e [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
solenberg7e4e01a2015-12-02 08:05:01 -080045#include "talk/media/webrtc/webrtcmediaengine.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000046#include "talk/media/webrtc/webrtcvoe.h"
Tommif888bb52015-12-12 01:37:01 +010047#include "webrtc/audio/audio_sink.h"
tfarina5237aaf2015-11-10 23:44:30 -080048#include "webrtc/base/arraysize.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000049#include "webrtc/base/base64.h"
50#include "webrtc/base/byteorder.h"
51#include "webrtc/base/common.h"
52#include "webrtc/base/helpers.h"
53#include "webrtc/base/logging.h"
54#include "webrtc/base/stringencode.h"
55#include "webrtc/base/stringutils.h"
ivoc112a3d82015-10-16 02:22:18 -070056#include "webrtc/call/rtc_event_log.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000057#include "webrtc/common.h"
solenberg26c8c912015-11-27 04:00:25 -080058#include "webrtc/modules/audio_coding/acm2/rent_a_codec.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010060#include "webrtc/system_wrappers/include/field_trial.h"
solenbergbd138382015-11-20 16:08:07 -080061#include "webrtc/system_wrappers/include/trace.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063namespace cricket {
solenbergd97ec302015-10-07 01:40:33 -070064namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065
solenbergbd138382015-11-20 16:08:07 -080066const int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |
67 webrtc::kTraceWarning | webrtc::kTraceError |
68 webrtc::kTraceCritical;
69const int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |
70 webrtc::kTraceInfo;
71
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072// On Windows Vista and newer, Microsoft introduced the concept of "Default
73// Communications Device". This means that there are two types of default
74// devices (old Wave Audio style default and Default Communications Device).
75//
76// On Windows systems which only support Wave Audio style default, uses either
77// -1 or 0 to select the default device.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078#ifdef WIN32
solenbergd97ec302015-10-07 01:40:33 -070079const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080#else
solenbergd97ec302015-10-07 01:40:33 -070081const int kDefaultAudioDeviceId = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082#endif
83
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084// Parameter used for NACK.
85// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
solenbergd97ec302015-10-07 01:40:33 -070086const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000087
88// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000089// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +000090
91// Recommended bitrates:
92// 8-12 kb/s for NB speech,
93// 16-20 kb/s for WB speech,
94// 28-40 kb/s for FB speech,
95// 48-64 kb/s for FB mono music, and
96// 64-128 kb/s for FB stereo music.
97// The current implementation applies the following values to mono signals,
98// and multiplies them by 2 for stereo.
solenbergd97ec302015-10-07 01:40:33 -070099const int kOpusBitrateNb = 12000;
100const int kOpusBitrateWb = 20000;
101const int kOpusBitrateFb = 32000;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000102
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000103// Opus bitrate should be in the range between 6000 and 510000.
solenbergd97ec302015-10-07 01:40:33 -0700104const int kOpusMinBitrate = 6000;
105const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000106
wu@webrtc.orgde305012013-10-31 15:40:38 +0000107// Default audio dscp value.
108// See http://tools.ietf.org/html/rfc2474 for details.
109// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
solenbergd97ec302015-10-07 01:40:33 -0700110const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000111
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000112// Ensure we open the file in a writeable path on ChromeOS and Android. This
113// workaround can be removed when it's possible to specify a filename for audio
114// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000115//
116// TODO(grunell): Use a string in the options instead of hardcoding it here
117// and let the embedder choose the filename (crbug.com/264223).
118//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000119// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
120// below.
121#if defined(CHROMEOS)
solenbergd97ec302015-10-07 01:40:33 -0700122const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000123#elif defined(ANDROID)
solenbergd97ec302015-10-07 01:40:33 -0700124const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000125#else
solenbergd97ec302015-10-07 01:40:33 -0700126const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000127#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000128
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100129// Constants from voice_engine_defines.h.
130const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
131const int kMaxTelephoneEventCode = 255;
132const int kMinTelephoneEventDuration = 100;
133const int kMaxTelephoneEventDuration = 60000; // Actual limit is 2^16
134
solenberg0b675462015-10-09 01:37:09 -0700135bool ValidateStreamParams(const StreamParams& sp) {
136 if (sp.ssrcs.empty()) {
137 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
138 return false;
139 }
140 if (sp.ssrcs.size() > 1) {
141 LOG(LS_ERROR) << "Multiple SSRCs in stream parameters: " << sp.ToString();
142 return false;
143 }
144 return true;
145}
146
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000147// Dumps an AudioCodec in RFC 2327-ish format.
solenbergd97ec302015-10-07 01:40:33 -0700148std::string ToString(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149 std::stringstream ss;
150 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
151 << " (" << codec.id << ")";
152 return ss.str();
153}
Minyue Li7100dcd2015-03-27 05:05:59 +0100154
solenbergd97ec302015-10-07 01:40:33 -0700155std::string ToString(const webrtc::CodecInst& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000156 std::stringstream ss;
157 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
158 << " (" << codec.pltype << ")";
159 return ss.str();
160}
161
solenbergd97ec302015-10-07 01:40:33 -0700162bool IsCodec(const AudioCodec& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100163 return (_stricmp(codec.name.c_str(), ref_name) == 0);
164}
165
solenbergd97ec302015-10-07 01:40:33 -0700166bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100167 return (_stricmp(codec.plname, ref_name) == 0);
168}
169
solenbergd97ec302015-10-07 01:40:33 -0700170bool FindCodec(const std::vector<AudioCodec>& codecs,
solenberg26c8c912015-11-27 04:00:25 -0800171 const AudioCodec& codec,
172 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200173 for (const AudioCodec& c : codecs) {
174 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200176 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177 }
178 return true;
179 }
180 }
181 return false;
182}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000183
solenberg0b675462015-10-09 01:37:09 -0700184bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
185 if (codecs.empty()) {
186 return true;
187 }
188 std::vector<int> payload_types;
189 for (const AudioCodec& codec : codecs) {
190 payload_types.push_back(codec.id);
191 }
192 std::sort(payload_types.begin(), payload_types.end());
193 auto it = std::unique(payload_types.begin(), payload_types.end());
194 return it == payload_types.end();
195}
196
solenbergd97ec302015-10-07 01:40:33 -0700197bool IsNackEnabled(const AudioCodec& codec) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000198 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
199 kParamValueEmpty));
200}
201
Minyue Li7100dcd2015-03-27 05:05:59 +0100202// Return true if codec.params[feature] == "1", false otherwise.
solenberg26c8c912015-11-27 04:00:25 -0800203bool IsCodecFeatureEnabled(const AudioCodec& codec, const char* feature) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100204 int value;
205 return codec.GetParam(feature, &value) && value == 1;
206}
207
208// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
209// otherwise. If the value (either from params or codec.bitrate) <=0, use the
210// default configuration. If the value is beyond feasible bit rate of Opus,
211// clamp it. Returns the Opus bit rate for operation.
solenbergd97ec302015-10-07 01:40:33 -0700212int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100213 int bitrate = 0;
214 bool use_param = true;
215 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
216 bitrate = codec.bitrate;
217 use_param = false;
218 }
219 if (bitrate <= 0) {
220 if (max_playback_rate <= 8000) {
221 bitrate = kOpusBitrateNb;
222 } else if (max_playback_rate <= 16000) {
223 bitrate = kOpusBitrateWb;
224 } else {
225 bitrate = kOpusBitrateFb;
226 }
227
228 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
229 bitrate *= 2;
230 }
231 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
232 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
233 std::string rate_source =
234 use_param ? "Codec parameter \"maxaveragebitrate\"" :
235 "Supplied Opus bitrate";
236 LOG(LS_WARNING) << rate_source
237 << " is invalid and is replaced by: "
238 << bitrate;
239 }
240 return bitrate;
241}
242
243// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
244// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
solenbergd97ec302015-10-07 01:40:33 -0700245int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100246 int value;
247 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
248 return value;
249 }
250 return kOpusDefaultMaxPlaybackRate;
251}
252
solenbergd97ec302015-10-07 01:40:33 -0700253void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
Minyue Li7100dcd2015-03-27 05:05:59 +0100254 bool* enable_codec_fec, int* max_playback_rate,
255 bool* enable_codec_dtx) {
256 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
257 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
258 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
259
260 // If OPUS, change what we send according to the "stereo" codec
261 // parameter, and not the "channels" parameter. We set
262 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
263 // the bitrate is not specified, i.e. is <= zero, we set it to the
264 // appropriate default value for mono or stereo Opus.
265
266 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
267 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
268}
269
solenberg566ef242015-11-06 15:34:49 -0800270webrtc::AudioState::Config MakeAudioStateConfig(VoEWrapper* voe_wrapper) {
271 webrtc::AudioState::Config config;
272 config.voice_engine = voe_wrapper->engine();
273 return config;
274}
275
solenberg26c8c912015-11-27 04:00:25 -0800276class WebRtcVoiceCodecs final {
277 public:
278 // TODO(solenberg): Do this filtering once off-line, add a simple AudioCodec
279 // list and add a test which verifies VoE supports the listed codecs.
280 static std::vector<AudioCodec> SupportedCodecs() {
281 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
282 std::vector<AudioCodec> result;
283 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
284 // Change the sample rate of G722 to 8000 to match SDP.
285 MaybeFixupG722(&voe_codec, 8000);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000286 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100287 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000288 continue;
289 }
290
291 const CodecPref* pref = NULL;
tfarina5237aaf2015-11-10 23:44:30 -0800292 for (size_t j = 0; j < arraysize(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100293 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000294 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
295 kCodecPrefs[j].channels == voe_codec.channels) {
296 pref = &kCodecPrefs[j];
297 break;
298 }
299 }
300
301 if (pref) {
302 // Use the payload type that we've configured in our pref table;
303 // use the offset in our pref table to determine the sort order.
tfarina5237aaf2015-11-10 23:44:30 -0800304 AudioCodec codec(
305 pref->payload_type, voe_codec.plname, voe_codec.plfreq,
306 voe_codec.rate, voe_codec.channels,
307 static_cast<int>(arraysize(kCodecPrefs)) - (pref - kCodecPrefs));
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000308 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100309 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000310 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000311 codec.bitrate = 0;
312 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100313 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000314 // Only add fmtp parameters that differ from the spec.
315 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
316 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000317 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000318 }
319 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
320 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000321 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000322 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000323 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000324
325 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000326 // when they can be set to values other than the default.
327 }
solenberg26c8c912015-11-27 04:00:25 -0800328 result.push_back(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000329 } else {
330 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
331 }
332 }
solenberg26c8c912015-11-27 04:00:25 -0800333 // Make sure they are in local preference order.
334 std::sort(result.begin(), result.end(), &AudioCodec::Preferable);
335 return result;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000336 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000337
solenberg26c8c912015-11-27 04:00:25 -0800338 static bool ToCodecInst(const AudioCodec& in,
339 webrtc::CodecInst* out) {
340 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
341 // Change the sample rate of G722 to 8000 to match SDP.
342 MaybeFixupG722(&voe_codec, 8000);
343 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
344 voe_codec.rate, voe_codec.channels, 0);
345 bool multi_rate = IsCodecMultiRate(voe_codec);
346 // Allow arbitrary rates for ISAC to be specified.
347 if (multi_rate) {
348 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
349 codec.bitrate = 0;
350 }
351 if (codec.Matches(in)) {
352 if (out) {
353 // Fixup the payload type.
354 voe_codec.pltype = in.id;
355
356 // Set bitrate if specified.
357 if (multi_rate && in.bitrate != 0) {
358 voe_codec.rate = in.bitrate;
359 }
360
361 // Reset G722 sample rate to 16000 to match WebRTC.
362 MaybeFixupG722(&voe_codec, 16000);
363
364 // Apply codec-specific settings.
365 if (IsCodec(codec, kIsacCodecName)) {
366 // If ISAC and an explicit bitrate is not specified,
367 // enable auto bitrate adjustment.
368 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
369 }
370 *out = voe_codec;
371 }
372 return true;
373 }
374 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000375 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000376 }
solenberg26c8c912015-11-27 04:00:25 -0800377
378 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
379 for (size_t i = 0; i < arraysize(kCodecPrefs); ++i) {
380 if (IsCodec(codec, kCodecPrefs[i].name) &&
381 kCodecPrefs[i].clockrate == codec.plfreq) {
382 return kCodecPrefs[i].is_multi_rate;
383 }
384 }
385 return false;
386 }
387
388 // If the AudioCodec param kCodecParamPTime is set, then we will set it to
389 // codec pacsize if it's valid, or we will pick the next smallest value we
390 // support.
391 // TODO(Brave): Query supported packet sizes from ACM when the API is ready.
392 static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
393 for (const CodecPref& codec_pref : kCodecPrefs) {
394 if ((IsCodec(*codec, codec_pref.name) &&
395 codec_pref.clockrate == codec->plfreq) ||
396 IsCodec(*codec, kG722CodecName)) {
397 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
398 if (packet_size_ms) {
399 // Convert unit from milli-seconds to samples.
400 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
401 return true;
402 }
403 }
404 }
405 return false;
406 }
407
408 private:
409 static const int kMaxNumPacketSize = 6;
410 struct CodecPref {
411 const char* name;
412 int clockrate;
Peter Kasting69558702016-01-12 16:26:35 -0800413 size_t channels;
solenberg26c8c912015-11-27 04:00:25 -0800414 int payload_type;
415 bool is_multi_rate;
416 int packet_sizes_ms[kMaxNumPacketSize];
417 };
418 // Note: keep the supported packet sizes in ascending order.
419 static const CodecPref kCodecPrefs[12];
420
421 static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
422 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
423 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
424 if (packet_size_ms && packet_size_ms <= ptime_ms) {
425 selected_packet_size_ms = packet_size_ms;
426 }
427 }
428 return selected_packet_size_ms;
429 }
430
431 // Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
432 // which says that G722 should be advertised as 8 kHz although it is a 16 kHz
433 // codec.
434 static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
435 if (IsCodec(*voe_codec, kG722CodecName)) {
436 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
437 // has changed, and this special case is no longer needed.
438 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
439 voe_codec->plfreq = new_plfreq;
440 }
441 }
442};
443
444const WebRtcVoiceCodecs::CodecPref WebRtcVoiceCodecs::kCodecPrefs[12] = {
445 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
446 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
447 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
448 // G722 should be advertised as 8000 Hz because of the RFC "bug".
449 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
450 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
451 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
452 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
453 { kCnCodecName, 32000, 1, 106, false, { } },
454 { kCnCodecName, 16000, 1, 105, false, { } },
455 { kCnCodecName, 8000, 1, 13, false, { } },
456 { kRedCodecName, 8000, 1, 127, false, { } },
457 { kDtmfCodecName, 8000, 1, 126, false, { } },
458};
459} // namespace {
460
461bool WebRtcVoiceEngine::ToCodecInst(const AudioCodec& in,
462 webrtc::CodecInst* out) {
463 return WebRtcVoiceCodecs::ToCodecInst(in, out);
464}
465
466WebRtcVoiceEngine::WebRtcVoiceEngine()
467 : voe_wrapper_(new VoEWrapper()),
468 audio_state_(webrtc::AudioState::Create(MakeAudioStateConfig(voe()))) {
469 Construct();
470}
471
472WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper)
473 : voe_wrapper_(voe_wrapper) {
474 Construct();
475}
476
477void WebRtcVoiceEngine::Construct() {
478 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
479 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
480
481 signal_thread_checker_.DetachFromThread();
482 std::memset(&default_agc_config_, 0, sizeof(default_agc_config_));
solenberg246b8172015-12-08 09:50:23 -0800483 voe_config_.Set<webrtc::VoicePacing>(new webrtc::VoicePacing(true));
solenberg26c8c912015-11-27 04:00:25 -0800484
485 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
486 webrtc::Trace::SetTraceCallback(this);
487
488 // Load our audio codec list.
489 codecs_ = WebRtcVoiceCodecs::SupportedCodecs();
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000490}
491
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000492WebRtcVoiceEngine::~WebRtcVoiceEngine() {
solenberg566ef242015-11-06 15:34:49 -0800493 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000494 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000495 if (adm_) {
496 voe_wrapper_.reset();
497 adm_->Release();
498 adm_ = NULL;
499 }
solenbergbd138382015-11-20 16:08:07 -0800500 webrtc::Trace::SetTraceCallback(nullptr);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000501}
502
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000503bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
solenberg566ef242015-11-06 15:34:49 -0800504 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700505 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000506 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
507 bool res = InitInternal();
508 if (res) {
509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
510 } else {
511 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
512 Terminate();
513 }
514 return res;
515}
516
517bool WebRtcVoiceEngine::InitInternal() {
solenberg566ef242015-11-06 15:34:49 -0800518 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000519 // Temporarily turn logging level up for the Init call
solenbergbd138382015-11-20 16:08:07 -0800520 webrtc::Trace::set_level_filter(kElevatedTraceFilter);
solenberg2515af22015-12-02 06:19:36 -0800521 LOG(LS_INFO) << webrtc::VoiceEngine::GetVersionString();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000522 if (voe_wrapper_->base()->Init(adm_) == -1) {
523 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000524 return false;
525 }
solenbergbd138382015-11-20 16:08:07 -0800526 webrtc::Trace::set_level_filter(kDefaultTraceFilter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000527
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528 // Save the default AGC configuration settings. This must happen before
solenberg246b8172015-12-08 09:50:23 -0800529 // calling ApplyOptions or the default will be overwritten.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000530 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
531 LOG_RTCERR0(GetAgcConfig);
532 return false;
533 }
534
solenberg0f7d2932016-01-15 01:40:39 -0800535 // Set default engine options.
536 {
537 AudioOptions options;
538 options.echo_cancellation = rtc::Optional<bool>(true);
539 options.auto_gain_control = rtc::Optional<bool>(true);
540 options.noise_suppression = rtc::Optional<bool>(true);
541 options.highpass_filter = rtc::Optional<bool>(true);
542 options.stereo_swapping = rtc::Optional<bool>(false);
543 options.audio_jitter_buffer_max_packets = rtc::Optional<int>(50);
544 options.audio_jitter_buffer_fast_accelerate = rtc::Optional<bool>(false);
545 options.typing_detection = rtc::Optional<bool>(true);
546 options.adjust_agc_delta = rtc::Optional<int>(0);
547 options.experimental_agc = rtc::Optional<bool>(false);
548 options.extended_filter_aec = rtc::Optional<bool>(false);
549 options.delay_agnostic_aec = rtc::Optional<bool>(false);
550 options.experimental_ns = rtc::Optional<bool>(false);
551 options.aec_dump = rtc::Optional<bool>(false);
552 if (!ApplyOptions(options)) {
553 return false;
554 }
555 }
556
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000557 // Print our codec list again for the call diagnostic log
558 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200559 for (const AudioCodec& codec : codecs_) {
560 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000561 }
562
solenberg246b8172015-12-08 09:50:23 -0800563 SetDefaultDevices();
564
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000565 initialized_ = true;
566 return true;
567}
568
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000569void WebRtcVoiceEngine::Terminate() {
solenberg566ef242015-11-06 15:34:49 -0800570 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000571 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
572 initialized_ = false;
573
574 StopAecDump();
575
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000576 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000577}
578
solenberg566ef242015-11-06 15:34:49 -0800579rtc::scoped_refptr<webrtc::AudioState>
580 WebRtcVoiceEngine::GetAudioState() const {
581 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
582 return audio_state_;
583}
584
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200585VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(webrtc::Call* call,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200586 const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -0800587 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -0700588 return new WebRtcVoiceMediaChannel(this, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000589}
590
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000591bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
solenberg566ef242015-11-06 15:34:49 -0800592 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikac14f5ff2015-09-23 14:08:33 +0200593 LOG(LS_INFO) << "ApplyOptions: " << options_in.ToString();
solenberg0f7d2932016-01-15 01:40:39 -0800594 AudioOptions options = options_in; // The options are modified below.
solenberg246b8172015-12-08 09:50:23 -0800595
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000596 // kEcConference is AEC with high suppression.
597 webrtc::EcModes ec_mode = webrtc::kEcConference;
598 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
599 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
600 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
kwiberg102c6a62015-10-30 02:47:38 -0700601 if (options.aecm_generate_comfort_noise) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000602 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
kwiberg102c6a62015-10-30 02:47:38 -0700603 << *options.aecm_generate_comfort_noise
604 << " (default is false).";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000605 }
606
kjellanderfcfc8042016-01-14 11:01:09 -0800607#if defined(WEBRTC_IOS)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000608 // On iOS, VPIO provides built-in EC and AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100609 options.echo_cancellation = rtc::Optional<bool>(false);
610 options.auto_gain_control = rtc::Optional<bool>(false);
henrika86d907c2015-09-07 16:09:50 +0200611 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000612#elif defined(ANDROID)
613 ec_mode = webrtc::kEcAecm;
614#endif
615
kjellanderfcfc8042016-01-14 11:01:09 -0800616#if defined(WEBRTC_IOS) || defined(ANDROID)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000617 // Set the AGC mode for iOS as well despite disabling it above, to avoid
618 // unsupported configuration errors from webrtc.
619 agc_mode = webrtc::kAgcFixedDigital;
Karl Wibergbe579832015-11-10 22:34:18 +0100620 options.typing_detection = rtc::Optional<bool>(false);
621 options.experimental_agc = rtc::Optional<bool>(false);
622 options.extended_filter_aec = rtc::Optional<bool>(false);
623 options.experimental_ns = rtc::Optional<bool>(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000624#endif
625
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100626 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
627 // where the feature is not supported.
628 bool use_delay_agnostic_aec = false;
kjellanderfcfc8042016-01-14 11:01:09 -0800629#if !defined(WEBRTC_IOS)
kwiberg102c6a62015-10-30 02:47:38 -0700630 if (options.delay_agnostic_aec) {
631 use_delay_agnostic_aec = *options.delay_agnostic_aec;
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100632 if (use_delay_agnostic_aec) {
Karl Wibergbe579832015-11-10 22:34:18 +0100633 options.echo_cancellation = rtc::Optional<bool>(true);
634 options.extended_filter_aec = rtc::Optional<bool>(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100635 ec_mode = webrtc::kEcConference;
636 }
637 }
638#endif
639
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000640 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
641
kwiberg102c6a62015-10-30 02:47:38 -0700642 if (options.echo_cancellation) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000643 // Check if platform supports built-in EC. Currently only supported on
644 // Android and in combination with Java based audio layer.
645 // TODO(henrika): investigate possibility to support built-in EC also
646 // in combination with Open SL ES audio.
647 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200648 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200649 // Built-in EC exists on this device and use_delay_agnostic_aec is not
650 // overriding it. Enable/Disable it according to the echo_cancellation
651 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200652 const bool enable_built_in_aec =
kwiberg102c6a62015-10-30 02:47:38 -0700653 *options.echo_cancellation && !use_delay_agnostic_aec;
Bjorn Volcker73f72102015-06-03 14:50:15 +0200654 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
655 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100656 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000657 // i.e., replace the software EC with the built-in EC.
Karl Wibergbe579832015-11-10 22:34:18 +0100658 options.echo_cancellation = rtc::Optional<bool>(false);
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000659 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
660 }
661 }
kwiberg102c6a62015-10-30 02:47:38 -0700662 if (voep->SetEcStatus(*options.echo_cancellation, ec_mode) == -1) {
663 LOG_RTCERR2(SetEcStatus, *options.echo_cancellation, ec_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000664 return false;
665 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700666 LOG(LS_INFO) << "Echo control set to " << *options.echo_cancellation
henrika86d907c2015-09-07 16:09:50 +0200667 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000668 }
669#if !defined(ANDROID)
670 // TODO(ajm): Remove the error return on Android from webrtc.
kwiberg102c6a62015-10-30 02:47:38 -0700671 if (voep->SetEcMetricsStatus(*options.echo_cancellation) == -1) {
672 LOG_RTCERR1(SetEcMetricsStatus, *options.echo_cancellation);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000673 return false;
674 }
675#endif
676 if (ec_mode == webrtc::kEcAecm) {
kwiberg102c6a62015-10-30 02:47:38 -0700677 bool cn = options.aecm_generate_comfort_noise.value_or(false);
678 if (voep->SetAecmMode(aecm_mode, cn) != 0) {
679 LOG_RTCERR2(SetAecmMode, aecm_mode, cn);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000680 return false;
681 }
682 }
683 }
684
kwiberg102c6a62015-10-30 02:47:38 -0700685 if (options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200686 const bool built_in_agc = voe_wrapper_->hw()->BuiltInAGCIsAvailable();
687 if (built_in_agc) {
kwiberg102c6a62015-10-30 02:47:38 -0700688 if (voe_wrapper_->hw()->EnableBuiltInAGC(*options.auto_gain_control) ==
689 0 &&
690 *options.auto_gain_control) {
henrikac14f5ff2015-09-23 14:08:33 +0200691 // Disable internal software AGC if built-in AGC is enabled,
692 // i.e., replace the software AGC with the built-in AGC.
Karl Wibergbe579832015-11-10 22:34:18 +0100693 options.auto_gain_control = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200694 LOG(LS_INFO) << "Disabling AGC since built-in AGC will be used instead";
695 }
696 }
kwiberg102c6a62015-10-30 02:47:38 -0700697 if (voep->SetAgcStatus(*options.auto_gain_control, agc_mode) == -1) {
698 LOG_RTCERR2(SetAgcStatus, *options.auto_gain_control, agc_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000699 return false;
700 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700701 LOG(LS_INFO) << "Auto gain set to " << *options.auto_gain_control
702 << " with mode " << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000703 }
704 }
705
kwiberg102c6a62015-10-30 02:47:38 -0700706 if (options.tx_agc_target_dbov || options.tx_agc_digital_compression_gain ||
707 options.tx_agc_limiter) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000708 // Override default_agc_config_. Generally, an unset option means "leave
709 // the VoE bits alone" in this function, so we want whatever is set to be
710 // stored as the new "default". If we didn't, then setting e.g.
711 // tx_agc_target_dbov would reset digital compression gain and limiter
712 // settings.
713 // Also, if we don't update default_agc_config_, then adjust_agc_delta
714 // would be an offset from the original values, and not whatever was set
715 // explicitly.
kwiberg102c6a62015-10-30 02:47:38 -0700716 default_agc_config_.targetLeveldBOv = options.tx_agc_target_dbov.value_or(
717 default_agc_config_.targetLeveldBOv);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000718 default_agc_config_.digitalCompressionGaindB =
kwiberg102c6a62015-10-30 02:47:38 -0700719 options.tx_agc_digital_compression_gain.value_or(
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000720 default_agc_config_.digitalCompressionGaindB);
721 default_agc_config_.limiterEnable =
kwiberg102c6a62015-10-30 02:47:38 -0700722 options.tx_agc_limiter.value_or(default_agc_config_.limiterEnable);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000723 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
724 LOG_RTCERR3(SetAgcConfig,
725 default_agc_config_.targetLeveldBOv,
726 default_agc_config_.digitalCompressionGaindB,
727 default_agc_config_.limiterEnable);
728 return false;
729 }
730 }
731
kwiberg102c6a62015-10-30 02:47:38 -0700732 if (options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200733 const bool built_in_ns = voe_wrapper_->hw()->BuiltInNSIsAvailable();
734 if (built_in_ns) {
kwiberg102c6a62015-10-30 02:47:38 -0700735 if (voe_wrapper_->hw()->EnableBuiltInNS(*options.noise_suppression) ==
736 0 &&
737 *options.noise_suppression) {
henrikac14f5ff2015-09-23 14:08:33 +0200738 // Disable internal software NS if built-in NS is enabled,
739 // i.e., replace the software NS with the built-in NS.
Karl Wibergbe579832015-11-10 22:34:18 +0100740 options.noise_suppression = rtc::Optional<bool>(false);
henrikac14f5ff2015-09-23 14:08:33 +0200741 LOG(LS_INFO) << "Disabling NS since built-in NS will be used instead";
742 }
743 }
kwiberg102c6a62015-10-30 02:47:38 -0700744 if (voep->SetNsStatus(*options.noise_suppression, ns_mode) == -1) {
745 LOG_RTCERR2(SetNsStatus, *options.noise_suppression, ns_mode);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000746 return false;
747 } else {
kwiberg102c6a62015-10-30 02:47:38 -0700748 LOG(LS_INFO) << "Noise suppression set to " << *options.noise_suppression
henrikac14f5ff2015-09-23 14:08:33 +0200749 << " with mode " << ns_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000750 }
751 }
752
kwiberg102c6a62015-10-30 02:47:38 -0700753 if (options.highpass_filter) {
754 LOG(LS_INFO) << "High pass filter enabled? " << *options.highpass_filter;
755 if (voep->EnableHighPassFilter(*options.highpass_filter) == -1) {
756 LOG_RTCERR1(SetHighpassFilterStatus, *options.highpass_filter);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000757 return false;
758 }
759 }
760
kwiberg102c6a62015-10-30 02:47:38 -0700761 if (options.stereo_swapping) {
762 LOG(LS_INFO) << "Stereo swapping enabled? " << *options.stereo_swapping;
763 voep->EnableStereoChannelSwapping(*options.stereo_swapping);
764 if (voep->IsStereoChannelSwappingEnabled() != *options.stereo_swapping) {
765 LOG_RTCERR1(EnableStereoChannelSwapping, *options.stereo_swapping);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000766 return false;
767 }
768 }
769
kwiberg102c6a62015-10-30 02:47:38 -0700770 if (options.audio_jitter_buffer_max_packets) {
771 LOG(LS_INFO) << "NetEq capacity is "
772 << *options.audio_jitter_buffer_max_packets;
Henrik Lundin64dad832015-05-11 12:44:23 +0200773 voe_config_.Set<webrtc::NetEqCapacityConfig>(
kwiberg102c6a62015-10-30 02:47:38 -0700774 new webrtc::NetEqCapacityConfig(
775 *options.audio_jitter_buffer_max_packets));
Henrik Lundin64dad832015-05-11 12:44:23 +0200776 }
777
kwiberg102c6a62015-10-30 02:47:38 -0700778 if (options.audio_jitter_buffer_fast_accelerate) {
779 LOG(LS_INFO) << "NetEq fast mode? "
780 << *options.audio_jitter_buffer_fast_accelerate;
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200781 voe_config_.Set<webrtc::NetEqFastAccelerate>(
kwiberg102c6a62015-10-30 02:47:38 -0700782 new webrtc::NetEqFastAccelerate(
783 *options.audio_jitter_buffer_fast_accelerate));
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200784 }
785
kwiberg102c6a62015-10-30 02:47:38 -0700786 if (options.typing_detection) {
787 LOG(LS_INFO) << "Typing detection is enabled? "
788 << *options.typing_detection;
789 if (voep->SetTypingDetectionStatus(*options.typing_detection) == -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000790 // In case of error, log the info and continue
kwiberg102c6a62015-10-30 02:47:38 -0700791 LOG_RTCERR1(SetTypingDetectionStatus, *options.typing_detection);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000792 }
793 }
794
kwiberg102c6a62015-10-30 02:47:38 -0700795 if (options.adjust_agc_delta) {
796 LOG(LS_INFO) << "Adjust agc delta is " << *options.adjust_agc_delta;
797 if (!AdjustAgcLevel(*options.adjust_agc_delta)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000798 return false;
799 }
800 }
801
kwiberg102c6a62015-10-30 02:47:38 -0700802 if (options.aec_dump) {
803 LOG(LS_INFO) << "Aec dump is enabled? " << *options.aec_dump;
804 if (*options.aec_dump)
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000805 StartAecDump(kAecDumpByAudioOptionFilename);
806 else
807 StopAecDump();
808 }
809
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000810 webrtc::Config config;
811
kwiberg102c6a62015-10-30 02:47:38 -0700812 if (options.delay_agnostic_aec)
813 delay_agnostic_aec_ = options.delay_agnostic_aec;
814 if (delay_agnostic_aec_) {
815 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << *delay_agnostic_aec_;
henrik.lundin0f133b92015-07-02 00:17:55 -0700816 config.Set<webrtc::DelayAgnostic>(
kwiberg102c6a62015-10-30 02:47:38 -0700817 new webrtc::DelayAgnostic(*delay_agnostic_aec_));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100818 }
819
kwiberg102c6a62015-10-30 02:47:38 -0700820 if (options.extended_filter_aec) {
821 extended_filter_aec_ = options.extended_filter_aec;
822 }
823 if (extended_filter_aec_) {
824 LOG(LS_INFO) << "Extended filter aec is enabled? " << *extended_filter_aec_;
Henrik Lundin441f6342015-06-09 16:03:13 +0200825 config.Set<webrtc::ExtendedFilter>(
kwiberg102c6a62015-10-30 02:47:38 -0700826 new webrtc::ExtendedFilter(*extended_filter_aec_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000827 }
828
kwiberg102c6a62015-10-30 02:47:38 -0700829 if (options.experimental_ns) {
830 experimental_ns_ = options.experimental_ns;
831 }
832 if (experimental_ns_) {
833 LOG(LS_INFO) << "Experimental ns is enabled? " << *experimental_ns_;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000834 config.Set<webrtc::ExperimentalNs>(
kwiberg102c6a62015-10-30 02:47:38 -0700835 new webrtc::ExperimentalNs(*experimental_ns_));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000836 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000837
838 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
839 // returns NULL on audio_processing().
840 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
841 if (audioproc) {
842 audioproc->SetExtraOptions(config);
843 }
844
kwiberg102c6a62015-10-30 02:47:38 -0700845 if (options.recording_sample_rate) {
846 LOG(LS_INFO) << "Recording sample rate is "
847 << *options.recording_sample_rate;
848 if (voe_wrapper_->hw()->SetRecordingSampleRate(
849 *options.recording_sample_rate)) {
850 LOG_RTCERR1(SetRecordingSampleRate, *options.recording_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000851 }
852 }
853
kwiberg102c6a62015-10-30 02:47:38 -0700854 if (options.playout_sample_rate) {
855 LOG(LS_INFO) << "Playout sample rate is " << *options.playout_sample_rate;
856 if (voe_wrapper_->hw()->SetPlayoutSampleRate(
857 *options.playout_sample_rate)) {
858 LOG_RTCERR1(SetPlayoutSampleRate, *options.playout_sample_rate);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000859 }
860 }
861
862 return true;
863}
864
solenberg246b8172015-12-08 09:50:23 -0800865void WebRtcVoiceEngine::SetDefaultDevices() {
solenberg566ef242015-11-06 15:34:49 -0800866 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
kjellanderfcfc8042016-01-14 11:01:09 -0800867#if !defined(WEBRTC_IOS)
solenberg246b8172015-12-08 09:50:23 -0800868 int in_id = kDefaultAudioDeviceId;
869 int out_id = kDefaultAudioDeviceId;
870 LOG(LS_INFO) << "Setting microphone to (id=" << in_id
871 << ") and speaker to (id=" << out_id << ")";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000872
solenbergc1a1b352015-09-22 13:31:20 -0700873 bool ret = true;
solenberg246b8172015-12-08 09:50:23 -0800874 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
875 LOG_RTCERR1(SetRecordingDevice, in_id);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000876 ret = false;
877 }
solenberg246b8172015-12-08 09:50:23 -0800878 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
879 if (ap) {
880 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881 }
882
solenberg246b8172015-12-08 09:50:23 -0800883 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
884 LOG_RTCERR1(SetPlayoutDevice, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885 ret = false;
886 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 if (ret) {
solenberg246b8172015-12-08 09:50:23 -0800889 LOG(LS_INFO) << "Set microphone to (id=" << in_id
890 << ") and speaker to (id=" << out_id << ")";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 }
kjellanderfcfc8042016-01-14 11:01:09 -0800892#endif // !WEBRTC_IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000893}
894
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
solenberg566ef242015-11-06 15:34:49 -0800896 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897 unsigned int ulevel;
898 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
899 LOG_RTCERR1(GetSpeakerVolume, level);
900 return false;
901 }
902 *level = ulevel;
903 return true;
904}
905
906bool WebRtcVoiceEngine::SetOutputVolume(int level) {
solenberg566ef242015-11-06 15:34:49 -0800907 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrikg91d6ede2015-09-17 00:24:34 -0700908 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
910 LOG_RTCERR1(SetSpeakerVolume, level);
911 return false;
912 }
913 return true;
914}
915
916int WebRtcVoiceEngine::GetInputLevel() {
solenberg566ef242015-11-06 15:34:49 -0800917 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 unsigned int ulevel;
919 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
920 static_cast<int>(ulevel) : -1;
921}
922
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
solenberg566ef242015-11-06 15:34:49 -0800924 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 return codecs_;
926}
927
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100928RtpCapabilities WebRtcVoiceEngine::GetCapabilities() const {
solenberg566ef242015-11-06 15:34:49 -0800929 RTC_DCHECK(signal_thread_checker_.CalledOnValidThread());
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100930 RtpCapabilities capabilities;
931 capabilities.header_extensions.push_back(RtpHeaderExtension(
932 kRtpAudioLevelHeaderExtension, kRtpAudioLevelHeaderExtensionDefaultId));
933 capabilities.header_extensions.push_back(
934 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
935 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
Stefan Holmer9d69c3f2015-12-07 10:45:43 +0100936 return capabilities;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937}
938
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939int WebRtcVoiceEngine::GetLastEngineError() {
solenberg566ef242015-11-06 15:34:49 -0800940 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941 return voe_wrapper_->error();
942}
943
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
945 int length) {
solenberg566ef242015-11-06 15:34:49 -0800946 // Note: This callback can happen on any thread!
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000947 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000949 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000951 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000953 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000955 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956
957 // Skip past boilerplate prefix text
958 if (length < 72) {
959 std::string msg(trace, length);
960 LOG(LS_ERROR) << "Malformed webrtc log message: ";
961 LOG_V(sev) << msg;
962 } else {
963 std::string msg(trace + 71, length - 72);
Peter Boströmd5c75b12015-09-23 13:24:32 +0200964 LOG_V(sev) << "webrtc: " << msg;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 }
966}
967
solenberg63b34542015-09-29 06:06:31 -0700968void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800969 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
970 RTC_DCHECK(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 channels_.push_back(channel);
972}
973
solenberg63b34542015-09-29 06:06:31 -0700974void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel* channel) {
solenberg566ef242015-11-06 15:34:49 -0800975 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg63b34542015-09-29 06:06:31 -0700976 auto it = std::find(channels_.begin(), channels_.end(), channel);
solenberg566ef242015-11-06 15:34:49 -0800977 RTC_DCHECK(it != channels_.end());
978 channels_.erase(it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979}
980
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000981// Adjusts the default AGC target level by the specified delta.
982// NB: If we start messing with other config fields, we'll want
983// to save the current webrtc::AgcConfig as well.
984bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
solenberg566ef242015-11-06 15:34:49 -0800985 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986 webrtc::AgcConfig config = default_agc_config_;
987 config.targetLeveldBOv -= delta;
988
989 LOG(LS_INFO) << "Adjusting AGC level from default -"
990 << default_agc_config_.targetLeveldBOv << "dB to -"
991 << config.targetLeveldBOv << "dB";
992
993 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
994 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
995 return false;
996 }
997 return true;
998}
999
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001000bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
solenberg566ef242015-11-06 15:34:49 -08001001 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 if (initialized_) {
1003 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1004 return false;
1005 }
1006 if (adm_) {
1007 adm_->Release();
1008 adm_ = NULL;
1009 }
1010 if (adm) {
1011 adm_ = adm;
1012 adm_->AddRef();
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 return true;
1015}
1016
ivoca4df27b2015-12-19 10:14:10 -08001017bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001018 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001019 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001020 if (!aec_dump_file_stream) {
1021 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001022 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001023 LOG(LS_WARNING) << "Could not close file.";
1024 return false;
1025 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001026 StopAecDump();
ivoca4df27b2015-12-19 10:14:10 -08001027 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001028 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001029 LOG_RTCERR0(StartDebugRecording);
1030 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001031 return false;
1032 }
1033 is_dumping_aec_ = true;
1034 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001035}
1036
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
solenberg566ef242015-11-06 15:34:49 -08001038 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 if (!is_dumping_aec_) {
1040 // Start dumping AEC when we are not dumping.
ivoca4df27b2015-12-19 10:14:10 -08001041 if (voe_wrapper_->processing()->StartDebugRecording(
1042 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001043 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044 } else {
1045 is_dumping_aec_ = true;
1046 }
1047 }
1048}
1049
1050void WebRtcVoiceEngine::StopAecDump() {
solenberg566ef242015-11-06 15:34:49 -08001051 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 if (is_dumping_aec_) {
1053 // Stop dumping AEC when we are dumping.
ivoca4df27b2015-12-19 10:14:10 -08001054 if (voe_wrapper_->processing()->StopDebugRecording() !=
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055 webrtc::AudioProcessing::kNoError) {
1056 LOG_RTCERR0(StopDebugRecording);
1057 }
1058 is_dumping_aec_ = false;
1059 }
1060}
1061
ivoc112a3d82015-10-16 02:22:18 -07001062bool WebRtcVoiceEngine::StartRtcEventLog(rtc::PlatformFile file) {
solenberg566ef242015-11-06 15:34:49 -08001063 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc112a3d82015-10-16 02:22:18 -07001064 return voe_wrapper_->codec()->GetEventLog()->StartLogging(file);
1065}
1066
1067void WebRtcVoiceEngine::StopRtcEventLog() {
solenberg566ef242015-11-06 15:34:49 -08001068 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ivoc112a3d82015-10-16 02:22:18 -07001069 voe_wrapper_->codec()->GetEventLog()->StopLogging();
1070}
1071
solenberg0a617e22015-10-20 15:49:38 -07001072int WebRtcVoiceEngine::CreateVoEChannel() {
solenberg566ef242015-11-06 15:34:49 -08001073 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001074 return voe_wrapper_->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001075}
1076
solenbergc96df772015-10-21 13:01:53 -07001077class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001078 : public AudioRenderer::Sink {
1079 public:
solenbergc96df772015-10-21 13:01:53 -07001080 WebRtcAudioSendStream(int ch, webrtc::AudioTransport* voe_audio_transport,
solenberg3a941542015-11-16 07:34:50 -08001081 uint32_t ssrc, const std::string& c_name,
1082 const std::vector<webrtc::RtpExtension>& extensions,
1083 webrtc::Call* call)
solenberg7add0582015-11-20 09:59:34 -08001084 : voe_audio_transport_(voe_audio_transport),
solenberg3a941542015-11-16 07:34:50 -08001085 call_(call),
1086 config_(nullptr) {
solenberg85a04962015-10-27 03:35:21 -07001087 RTC_DCHECK_GE(ch, 0);
1088 // TODO(solenberg): Once we're not using FakeWebRtcVoiceEngine anymore:
1089 // RTC_DCHECK(voe_audio_transport);
solenbergc96df772015-10-21 13:01:53 -07001090 RTC_DCHECK(call);
solenberg85a04962015-10-27 03:35:21 -07001091 audio_capture_thread_checker_.DetachFromThread();
solenberg3a941542015-11-16 07:34:50 -08001092 config_.rtp.ssrc = ssrc;
1093 config_.rtp.c_name = c_name;
1094 config_.voe_channel_id = ch;
1095 RecreateAudioSendStream(extensions);
solenbergc96df772015-10-21 13:01:53 -07001096 }
solenberg3a941542015-11-16 07:34:50 -08001097
solenbergc96df772015-10-21 13:01:53 -07001098 ~WebRtcAudioSendStream() override {
solenberg566ef242015-11-06 15:34:49 -08001099 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001100 Stop();
1101 call_->DestroyAudioSendStream(stream_);
1102 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001103
solenberg3a941542015-11-16 07:34:50 -08001104 void RecreateAudioSendStream(
1105 const std::vector<webrtc::RtpExtension>& extensions) {
1106 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1107 if (stream_) {
1108 call_->DestroyAudioSendStream(stream_);
1109 stream_ = nullptr;
1110 }
1111 config_.rtp.extensions = extensions;
1112 RTC_DCHECK(!stream_);
1113 stream_ = call_->CreateAudioSendStream(config_);
1114 RTC_CHECK(stream_);
1115 }
1116
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001117 bool SendTelephoneEvent(int payload_type, uint8_t event,
1118 uint32_t duration_ms) {
1119 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1120 RTC_DCHECK(stream_);
1121 return stream_->SendTelephoneEvent(payload_type, event, duration_ms);
1122 }
1123
solenberg3a941542015-11-16 07:34:50 -08001124 webrtc::AudioSendStream::Stats GetStats() const {
1125 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1126 RTC_DCHECK(stream_);
1127 return stream_->GetStats();
1128 }
1129
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001130 // Starts the rendering by setting a sink to the renderer to get data
1131 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001132 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001133 // TODO(xians): Make sure Start() is called only once.
1134 void Start(AudioRenderer* renderer) {
solenberg566ef242015-11-06 15:34:49 -08001135 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001136 RTC_DCHECK(renderer);
1137 if (renderer_) {
henrikg91d6ede2015-09-17 00:24:34 -07001138 RTC_DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001139 return;
1140 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001141 renderer->SetSink(this);
1142 renderer_ = renderer;
1143 }
1144
solenbergc96df772015-10-21 13:01:53 -07001145 // Stops rendering by setting the sink of the renderer to nullptr. No data
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001146 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001147 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001148 void Stop() {
solenberg566ef242015-11-06 15:34:49 -08001149 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001150 if (renderer_) {
1151 renderer_->SetSink(nullptr);
1152 renderer_ = nullptr;
solenberg98c68862015-10-09 03:27:14 -07001153 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001154 }
1155
1156 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001157 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001158 void OnData(const void* audio_data,
1159 int bits_per_sample,
1160 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001161 size_t number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001162 size_t number_of_frames) override {
solenberg566ef242015-11-06 15:34:49 -08001163 RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07001164 RTC_DCHECK(audio_capture_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001165 RTC_DCHECK(voe_audio_transport_);
solenberg7add0582015-11-20 09:59:34 -08001166 voe_audio_transport_->OnData(config_.voe_channel_id,
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001167 audio_data,
1168 bits_per_sample,
1169 sample_rate,
1170 number_of_channels,
1171 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001172 }
1173
1174 // Callback from the |renderer_| when it is going away. In case Start() has
1175 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001176 void OnClose() override {
solenberg566ef242015-11-06 15:34:49 -08001177 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07001178 // Set |renderer_| to nullptr to make sure no more callback will get into
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001179 // the renderer.
solenbergc96df772015-10-21 13:01:53 -07001180 renderer_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001181 }
1182
1183 // Accessor to the VoE channel ID.
solenberg85a04962015-10-27 03:35:21 -07001184 int channel() const {
solenberg566ef242015-11-06 15:34:49 -08001185 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08001186 return config_.voe_channel_id;
solenberg85a04962015-10-27 03:35:21 -07001187 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001188
1189 private:
solenberg566ef242015-11-06 15:34:49 -08001190 rtc::ThreadChecker worker_thread_checker_;
solenberg85a04962015-10-27 03:35:21 -07001191 rtc::ThreadChecker audio_capture_thread_checker_;
solenbergc96df772015-10-21 13:01:53 -07001192 webrtc::AudioTransport* const voe_audio_transport_ = nullptr;
1193 webrtc::Call* call_ = nullptr;
solenberg3a941542015-11-16 07:34:50 -08001194 webrtc::AudioSendStream::Config config_;
1195 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1196 // configuration changes.
solenbergc96df772015-10-21 13:01:53 -07001197 webrtc::AudioSendStream* stream_ = nullptr;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001198
1199 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1200 // PeerConnection will make sure invalidating the pointer before the object
1201 // goes away.
solenbergc96df772015-10-21 13:01:53 -07001202 AudioRenderer* renderer_ = nullptr;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001203
solenbergc96df772015-10-21 13:01:53 -07001204 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioSendStream);
1205};
1206
1207class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1208 public:
solenberg7add0582015-11-20 09:59:34 -08001209 WebRtcAudioReceiveStream(int ch, uint32_t remote_ssrc, uint32_t local_ssrc,
1210 bool use_combined_bwe, const std::string& sync_group,
1211 const std::vector<webrtc::RtpExtension>& extensions,
1212 webrtc::Call* call)
1213 : call_(call),
1214 config_() {
1215 RTC_DCHECK_GE(ch, 0);
1216 RTC_DCHECK(call);
1217 config_.rtp.remote_ssrc = remote_ssrc;
1218 config_.rtp.local_ssrc = local_ssrc;
1219 config_.voe_channel_id = ch;
1220 config_.sync_group = sync_group;
1221 RecreateAudioReceiveStream(use_combined_bwe, extensions);
1222 }
solenbergc96df772015-10-21 13:01:53 -07001223
solenberg7add0582015-11-20 09:59:34 -08001224 ~WebRtcAudioReceiveStream() {
1225 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1226 call_->DestroyAudioReceiveStream(stream_);
1227 }
1228
1229 void RecreateAudioReceiveStream(
1230 const std::vector<webrtc::RtpExtension>& extensions) {
1231 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1232 RecreateAudioReceiveStream(config_.combined_audio_video_bwe, extensions);
1233 }
1234 void RecreateAudioReceiveStream(bool use_combined_bwe) {
1235 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1236 RecreateAudioReceiveStream(use_combined_bwe, config_.rtp.extensions);
1237 }
1238
1239 webrtc::AudioReceiveStream::Stats GetStats() const {
1240 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1241 RTC_DCHECK(stream_);
1242 return stream_->GetStats();
1243 }
1244
1245 int channel() const {
1246 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1247 return config_.voe_channel_id;
1248 }
solenbergc96df772015-10-21 13:01:53 -07001249
deadbeef2d110be2016-01-13 12:00:26 -08001250 void SetRawAudioSink(rtc::scoped_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01001251 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
deadbeef2d110be2016-01-13 12:00:26 -08001252 stream_->SetSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01001253 }
1254
solenbergc96df772015-10-21 13:01:53 -07001255 private:
solenberg7add0582015-11-20 09:59:34 -08001256 void RecreateAudioReceiveStream(bool use_combined_bwe,
1257 const std::vector<webrtc::RtpExtension>& extensions) {
1258 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
1259 if (stream_) {
1260 call_->DestroyAudioReceiveStream(stream_);
1261 stream_ = nullptr;
1262 }
1263 config_.rtp.extensions = extensions;
1264 config_.combined_audio_video_bwe = use_combined_bwe;
1265 RTC_DCHECK(!stream_);
1266 stream_ = call_->CreateAudioReceiveStream(config_);
1267 RTC_CHECK(stream_);
1268 }
1269
1270 rtc::ThreadChecker worker_thread_checker_;
1271 webrtc::Call* call_ = nullptr;
1272 webrtc::AudioReceiveStream::Config config_;
1273 // The stream is owned by WebRtcAudioReceiveStream and may be reallocated if
1274 // configuration changes.
1275 webrtc::AudioReceiveStream* stream_ = nullptr;
solenbergc96df772015-10-21 13:01:53 -07001276
1277 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioReceiveStream);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001278};
1279
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001280WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001281 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001282 webrtc::Call* call)
solenberg566ef242015-11-06 15:34:49 -08001283 : engine_(engine), call_(call) {
solenberg0a617e22015-10-20 15:49:38 -07001284 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
solenberg566ef242015-11-06 15:34:49 -08001285 RTC_DCHECK(call);
solenberg0a617e22015-10-20 15:49:38 -07001286 engine->RegisterChannel(this);
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001287 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288}
1289
1290WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
solenberg566ef242015-11-06 15:34:49 -08001291 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001292 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
solenberg7add0582015-11-20 09:59:34 -08001293 // TODO(solenberg): Should be able to delete the streams directly, without
1294 // going through RemoveNnStream(), once stream objects handle
1295 // all (de)configuration.
solenbergc96df772015-10-21 13:01:53 -07001296 while (!send_streams_.empty()) {
1297 RemoveSendStream(send_streams_.begin()->first);
solenbergd97ec302015-10-07 01:40:33 -07001298 }
solenberg7add0582015-11-20 09:59:34 -08001299 while (!recv_streams_.empty()) {
1300 RemoveRecvStream(recv_streams_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301 }
solenberg0a617e22015-10-20 15:49:38 -07001302 engine()->UnregisterChannel(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303}
1304
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001305bool WebRtcVoiceMediaChannel::SetSendParameters(
1306 const AudioSendParameters& params) {
solenberg566ef242015-11-06 15:34:49 -08001307 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001308 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1309 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001310 // TODO(pthatcher): Refactor this to be more clean now that we have
1311 // all the information at once.
solenberg3a941542015-11-16 07:34:50 -08001312
1313 if (!SetSendCodecs(params.codecs)) {
1314 return false;
1315 }
1316
solenberg7e4e01a2015-12-02 08:05:01 -08001317 if (!ValidateRtpExtensions(params.extensions)) {
1318 return false;
1319 }
1320 std::vector<webrtc::RtpExtension> filtered_extensions =
1321 FilterRtpExtensions(params.extensions,
1322 webrtc::RtpExtension::IsSupportedForAudio, true);
1323 if (send_rtp_extensions_ != filtered_extensions) {
1324 send_rtp_extensions_.swap(filtered_extensions);
solenberg3a941542015-11-16 07:34:50 -08001325 for (auto& it : send_streams_) {
1326 it.second->RecreateAudioSendStream(send_rtp_extensions_);
1327 }
1328 }
1329
1330 if (!SetMaxSendBandwidth(params.max_bandwidth_bps)) {
1331 return false;
1332 }
1333 return SetOptions(params.options);
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001334}
1335
1336bool WebRtcVoiceMediaChannel::SetRecvParameters(
1337 const AudioRecvParameters& params) {
solenberg566ef242015-11-06 15:34:49 -08001338 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7e4e01a2015-12-02 08:05:01 -08001339 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1340 << params.ToString();
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001341 // TODO(pthatcher): Refactor this to be more clean now that we have
1342 // all the information at once.
solenberg7add0582015-11-20 09:59:34 -08001343
1344 if (!SetRecvCodecs(params.codecs)) {
1345 return false;
1346 }
1347
solenberg7e4e01a2015-12-02 08:05:01 -08001348 if (!ValidateRtpExtensions(params.extensions)) {
1349 return false;
1350 }
1351 std::vector<webrtc::RtpExtension> filtered_extensions =
1352 FilterRtpExtensions(params.extensions,
1353 webrtc::RtpExtension::IsSupportedForAudio, false);
1354 if (recv_rtp_extensions_ != filtered_extensions) {
1355 recv_rtp_extensions_.swap(filtered_extensions);
solenberg7add0582015-11-20 09:59:34 -08001356 for (auto& it : recv_streams_) {
1357 it.second->RecreateAudioReceiveStream(recv_rtp_extensions_);
1358 }
1359 }
1360
1361 return true;
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001362}
1363
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
solenberg566ef242015-11-06 15:34:49 -08001365 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 LOG(LS_INFO) << "Setting voice channel options: "
1367 << options.ToString();
1368
wu@webrtc.orgde305012013-10-31 15:40:38 +00001369 // Check if DSCP value is changed from previous.
1370 bool dscp_option_changed = (options_.dscp != options.dscp);
1371
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 // We retain all of the existing options, and apply the given ones
1373 // on top. This means there is no way to "clear" options such that
1374 // they go back to the engine default.
1375 options_.SetAll(options);
solenberg246b8172015-12-08 09:50:23 -08001376 if (!engine()->ApplyOptions(options_)) {
1377 LOG(LS_WARNING) <<
1378 "Failed to apply engine options during channel SetOptions.";
1379 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 }
1381
wu@webrtc.orgde305012013-10-31 15:40:38 +00001382 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001383 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
solenberg246b8172015-12-08 09:50:23 -08001384 if (options_.dscp.value_or(false)) {
wu@webrtc.orgde305012013-10-31 15:40:38 +00001385 dscp = kAudioDscpValue;
solenberg246b8172015-12-08 09:50:23 -08001386 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001387 if (MediaChannel::SetDscp(dscp) != 0) {
1388 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1389 }
1390 }
solenberg8fb30c32015-10-13 03:06:58 -07001391
solenbergc96df772015-10-21 13:01:53 -07001392 // TODO(solenberg): Don't recreate unless options changed.
solenberg7add0582015-11-20 09:59:34 -08001393 for (auto& it : recv_streams_) {
1394 it.second->RecreateAudioReceiveStream(
1395 options_.combined_audio_video_bwe.value_or(false));
1396 }
solenberg8fb30c32015-10-13 03:06:58 -07001397
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 LOG(LS_INFO) << "Set voice channel options. Current options: "
1399 << options_.ToString();
1400 return true;
1401}
1402
1403bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1404 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001405 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg8fb30c32015-10-13 03:06:58 -07001406
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 // Set the payload types to be used for incoming media.
solenberg0b675462015-10-09 01:37:09 -07001408 LOG(LS_INFO) << "Setting receive voice codecs.";
solenberg0b675462015-10-09 01:37:09 -07001409
1410 if (!VerifyUniquePayloadTypes(codecs)) {
1411 LOG(LS_ERROR) << "Codec payload types overlap.";
1412 return false;
1413 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414
1415 std::vector<AudioCodec> new_codecs;
1416 // Find all new codecs. We allow adding new codecs but don't allow changing
1417 // the payload type of codecs that is already configured since we might
1418 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001419 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001421 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1422 if (old_codec.id != codec.id) {
1423 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 return false;
1425 }
1426 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001427 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 }
1429 }
1430 if (new_codecs.empty()) {
1431 // There are no new codecs to configure. Already configured codecs are
1432 // never removed.
1433 return true;
1434 }
1435
1436 if (playout_) {
1437 // Receive codecs can not be changed while playing. So we temporarily
1438 // pause playout.
1439 PausePlayout();
1440 }
1441
solenberg26c8c912015-11-27 04:00:25 -08001442 bool result = true;
1443 for (const AudioCodec& codec : new_codecs) {
1444 webrtc::CodecInst voe_codec;
1445 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
1446 LOG(LS_INFO) << ToString(codec);
1447 voe_codec.pltype = codec.id;
1448 for (const auto& ch : recv_streams_) {
1449 if (engine()->voe()->codec()->SetRecPayloadType(
1450 ch.second->channel(), voe_codec) == -1) {
1451 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
1452 ToString(voe_codec));
1453 result = false;
1454 }
1455 }
1456 } else {
1457 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
1458 result = false;
1459 break;
1460 }
1461 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001462 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 recv_codecs_ = codecs;
1464 }
1465
1466 if (desired_playout_ && !playout_) {
1467 ResumePlayout();
1468 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001469 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470}
1471
1472bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001473 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001474 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001475 engine()->voe()->codec()->SetVADStatus(channel, false);
1476 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001477 engine()->voe()->rtp()->SetREDStatus(channel, false);
1478 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479
1480 // Scan through the list to figure out the codec to use for sending, along
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001481 // with the proper configuration for VAD.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001482 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 webrtc::CodecInst send_codec;
1484 memset(&send_codec, 0, sizeof(send_codec));
1485
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001486 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001487 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001488 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001489 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001490
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001491 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001492 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 // Ignore codecs we don't know about. The negotiation step should prevent
1494 // this, but double-check to be sure.
1495 webrtc::CodecInst voe_codec;
solenberg26c8c912015-11-27 04:00:25 -08001496 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001497 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498 continue;
1499 }
1500
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001501 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001502 // Skip telephone-event/CN codec, which will be handled later.
1503 continue;
1504 }
1505
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001506 // We'll use the first codec in the list to actually send audio data.
1507 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001508 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001509 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001510 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001511 // Parse out the RED parameters. If we fail, just ignore RED;
1512 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001513 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001514 continue;
1515 }
1516
1517 // Enable redundant encoding of the specified codec. Treat any
1518 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001519 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001520 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1521 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001522 return false;
1523 }
1524 } else {
1525 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001526 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001527 // For Opus as the send codec, we are to determine inband FEC, maximum
1528 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001529 if (IsCodec(codec, kOpusCodecName)) {
1530 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001531 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001532 }
Brave Yao5225dd82015-03-26 07:39:19 +08001533
1534 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1535 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001536 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
solenberg26c8c912015-11-27 04:00:25 -08001537 if (!WebRtcVoiceCodecs::SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001538 LOG(LS_WARNING) << "Failed to set packet size for codec "
1539 << send_codec.plname;
1540 return false;
1541 }
1542 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001543 }
1544 found_send_codec = true;
1545 break;
1546 }
1547
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001548 if (nack_enabled_ != nack_enabled) {
1549 SetNack(channel, nack_enabled);
1550 nack_enabled_ = nack_enabled;
1551 }
1552
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001553 if (!found_send_codec) {
1554 LOG(LS_WARNING) << "Received empty list of codecs.";
1555 return false;
1556 }
1557
1558 // Set the codec immediately, since SetVADStatus() depends on whether
1559 // the current codec is mono or stereo.
1560 if (!SetSendCodec(channel, send_codec))
1561 return false;
1562
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001563 // FEC should be enabled after SetSendCodec.
1564 if (enable_codec_fec) {
1565 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1566 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001567 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1568 // Enable codec internal FEC. Treat any failure as fatal internal error.
1569 LOG_RTCERR2(SetFECStatus, channel, true);
1570 return false;
1571 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001572 }
1573
Minyue Li7100dcd2015-03-27 05:05:59 +01001574 if (IsCodec(send_codec, kOpusCodecName)) {
1575 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1576 // send codec has to be Opus.
1577
1578 // Set Opus internal DTX.
1579 LOG(LS_INFO) << "Attempt to "
solenbergbd138382015-11-20 16:08:07 -08001580 << (enable_opus_dtx ? "enable" : "disable")
Minyue Li7100dcd2015-03-27 05:05:59 +01001581 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001582 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001583 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1584 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
1585 return false;
1586 }
1587
1588 // If opus_max_playback_rate <= 0, the default maximum playback rate
1589 // (48 kHz) will be used.
1590 if (opus_max_playback_rate > 0) {
1591 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1592 << opus_max_playback_rate
1593 << " Hz on channel "
1594 << channel;
1595 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1596 channel, opus_max_playback_rate) == -1) {
1597 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
1598 return false;
1599 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001600 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001601 }
1602
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001603 // Always update the |send_codec_| to the currently set send codec.
1604 send_codec_.reset(new webrtc::CodecInst(send_codec));
1605
minyue@webrtc.org26236952014-10-29 02:27:08 +00001606 if (send_bitrate_setting_) {
1607 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001608 }
1609
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001610 // Loop through the codecs list again to config the CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001611 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001612 // Ignore codecs we don't know about. The negotiation step should prevent
1613 // this, but double-check to be sure.
1614 webrtc::CodecInst voe_codec;
solenberg26c8c912015-11-27 04:00:25 -08001615 if (!WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001616 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001617 continue;
1618 }
1619
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001620 if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001621 // Turn voice activity detection/comfort noise on if supported.
1622 // Set the wideband CN payload type appropriately.
1623 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001624 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001625 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 case 8000:
1627 cn_freq = webrtc::kFreq8000Hz;
1628 break;
1629 case 16000:
1630 cn_freq = webrtc::kFreq16000Hz;
1631 break;
1632 case 32000:
1633 cn_freq = webrtc::kFreq32000Hz;
1634 break;
1635 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001636 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637 << " not supported.";
1638 continue;
1639 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001640 // Set the CN payloadtype and the VAD status.
1641 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1642 if (cn_freq != webrtc::kFreq8000Hz) {
1643 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001644 channel, codec.id, cn_freq) == -1) {
1645 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001646 // TODO(ajm): This failure condition will be removed from VoE.
1647 // Restore the return here when we update to a new enough webrtc.
1648 //
1649 // Not returning false because the SetSendCNPayloadType will fail if
1650 // the channel is already sending.
1651 // This can happen if the remote description is applied twice, for
1652 // example in the case of ROAP on top of JSEP, where both side will
1653 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001654 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001655 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001656 // Only turn on VAD if we have a CN payload type that matches the
1657 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001658 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01001659 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1660 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001661 LOG(LS_INFO) << "Enabling VAD";
1662 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1663 LOG_RTCERR2(SetVADStatus, channel, true);
1664 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001665 }
1666 }
1667 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001668 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001669 return true;
1670}
1671
1672bool WebRtcVoiceMediaChannel::SetSendCodecs(
1673 const std::vector<AudioCodec>& codecs) {
solenberg566ef242015-11-06 15:34:49 -08001674 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001675 // TODO(solenberg): Validate input - that payload types don't overlap, are
1676 // within range, filter out codecs we don't support,
1677 // redundant codecs etc.
solenbergd97ec302015-10-07 01:40:33 -07001678
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001679 // Find the DTMF telephone event "codec" payload type.
1680 dtmf_payload_type_ = rtc::Optional<int>();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001681 for (const AudioCodec& codec : codecs) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001682 if (IsCodec(codec, kDtmfCodecName)) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01001683 dtmf_payload_type_ = rtc::Optional<int>(codec.id);
1684 break;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001685 }
1686 }
1687
1688 // Cache the codecs in order to configure the channel created later.
1689 send_codecs_ = codecs;
solenbergc96df772015-10-21 13:01:53 -07001690 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001691 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001692 return false;
1693 }
1694 }
1695
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001696 // Set nack status on receive channels and update |nack_enabled_|.
solenberg7add0582015-11-20 09:59:34 -08001697 for (const auto& ch : recv_streams_) {
solenberg0a617e22015-10-20 15:49:38 -07001698 SetNack(ch.second->channel(), nack_enabled_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001699 }
solenberg0a617e22015-10-20 15:49:38 -07001700
1701 return true;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001702}
1703
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001704void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001706 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1708 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001709 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001710 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1711 }
1712}
1713
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714bool WebRtcVoiceMediaChannel::SetSendCodec(
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001715 int channel, const webrtc::CodecInst& send_codec) {
1716 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1717 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1718
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001719 webrtc::CodecInst current_codec;
1720 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1721 (send_codec == current_codec)) {
1722 // Codec is already configured, we can return without setting it again.
1723 return true;
1724 }
1725
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001726 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1727 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728 return false;
1729 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730 return true;
1731}
1732
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1734 desired_playout_ = playout;
1735 return ChangePlayout(desired_playout_);
1736}
1737
1738bool WebRtcVoiceMediaChannel::PausePlayout() {
1739 return ChangePlayout(false);
1740}
1741
1742bool WebRtcVoiceMediaChannel::ResumePlayout() {
1743 return ChangePlayout(desired_playout_);
1744}
1745
1746bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
solenberg566ef242015-11-06 15:34:49 -08001747 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001748 if (playout_ == playout) {
1749 return true;
1750 }
1751
solenberg7add0582015-11-20 09:59:34 -08001752 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001753 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001754 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001755 << ch.second->channel() << " failed";
solenberg1ac56142015-10-13 03:58:19 -07001756 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 }
1758 }
solenberg1ac56142015-10-13 03:58:19 -07001759 playout_ = playout;
1760 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761}
1762
1763bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
1764 desired_send_ = send;
solenbergc96df772015-10-21 13:01:53 -07001765 if (!send_streams_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766 return ChangeSend(desired_send_);
solenbergc96df772015-10-21 13:01:53 -07001767 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768 return true;
1769}
1770
1771bool WebRtcVoiceMediaChannel::PauseSend() {
1772 return ChangeSend(SEND_NOTHING);
1773}
1774
1775bool WebRtcVoiceMediaChannel::ResumeSend() {
1776 return ChangeSend(desired_send_);
1777}
1778
1779bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
1780 if (send_ == send) {
1781 return true;
1782 }
1783
solenberg246b8172015-12-08 09:50:23 -08001784 // Apply channel specific options when channel is enabled for sending.
solenberg63b34542015-09-29 06:06:31 -07001785 if (send == SEND_MICROPHONE) {
1786 engine()->ApplyOptions(options_);
1787 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001789 // Change the settings on each send channel.
solenbergc96df772015-10-21 13:01:53 -07001790 for (const auto& ch : send_streams_) {
solenberg63b34542015-09-29 06:06:31 -07001791 if (!ChangeSend(ch.second->channel(), send)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792 return false;
solenberg63b34542015-09-29 06:06:31 -07001793 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796 send_ = send;
1797 return true;
1798}
1799
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001800bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
1801 if (send == SEND_MICROPHONE) {
1802 if (engine()->voe()->base()->StartSend(channel) == -1) {
1803 LOG_RTCERR1(StartSend, channel);
1804 return false;
1805 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001806 } else { // SEND_NOTHING
henrikg91d6ede2015-09-17 00:24:34 -07001807 RTC_DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001808 if (engine()->voe()->base()->StopSend(channel) == -1) {
1809 LOG_RTCERR1(StopSend, channel);
1810 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 }
1812 }
1813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 return true;
1815}
1816
Peter Boström0c4e06b2015-10-07 12:23:21 +02001817bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1818 bool enable,
solenberg1dd98f32015-09-10 01:57:14 -07001819 const AudioOptions* options,
1820 AudioRenderer* renderer) {
solenberg566ef242015-11-06 15:34:49 -08001821 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1dd98f32015-09-10 01:57:14 -07001822 // TODO(solenberg): The state change should be fully rolled back if any one of
1823 // these calls fail.
1824 if (!SetLocalRenderer(ssrc, renderer)) {
1825 return false;
1826 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001827 if (!MuteStream(ssrc, !enable)) {
solenberg1dd98f32015-09-10 01:57:14 -07001828 return false;
1829 }
solenbergdfc8f4f2015-10-01 02:31:10 -07001830 if (enable && options) {
solenberg1dd98f32015-09-10 01:57:14 -07001831 return SetOptions(*options);
1832 }
1833 return true;
1834}
1835
solenberg0a617e22015-10-20 15:49:38 -07001836int WebRtcVoiceMediaChannel::CreateVoEChannel() {
1837 int id = engine()->CreateVoEChannel();
1838 if (id == -1) {
1839 LOG_RTCERR0(CreateVoEChannel);
1840 return -1;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001841 }
solenberg0a617e22015-10-20 15:49:38 -07001842 if (engine()->voe()->network()->RegisterExternalTransport(id, *this) == -1) {
1843 LOG_RTCERR2(RegisterExternalTransport, id, this);
1844 engine()->voe()->base()->DeleteChannel(id);
1845 return -1;
1846 }
1847 return id;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001848}
1849
solenberg7add0582015-11-20 09:59:34 -08001850bool WebRtcVoiceMediaChannel::DeleteVoEChannel(int channel) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001851 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
1852 LOG_RTCERR1(DeRegisterExternalTransport, channel);
1853 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001854 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
1855 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 return false;
1857 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001858 return true;
1859}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001860
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001861bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
solenberg566ef242015-11-06 15:34:49 -08001862 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07001863 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1864
1865 uint32_t ssrc = sp.first_ssrc();
1866 RTC_DCHECK(0 != ssrc);
1867
1868 if (GetSendChannelId(ssrc) != -1) {
1869 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001870 return false;
1871 }
1872
solenberg0a617e22015-10-20 15:49:38 -07001873 // Create a new channel for sending audio data.
1874 int channel = CreateVoEChannel();
1875 if (channel == -1) {
1876 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001877 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001878
solenbergc96df772015-10-21 13:01:53 -07001879 // Save the channel to send_streams_, so that RemoveSendStream() can still
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001880 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001881 webrtc::AudioTransport* audio_transport =
1882 engine()->voe()->base()->audio_transport();
solenberg3a941542015-11-16 07:34:50 -08001883 send_streams_.insert(std::make_pair(ssrc, new WebRtcAudioSendStream(
1884 channel, audio_transport, ssrc, sp.cname, send_rtp_extensions_, call_)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001885
solenberg0a617e22015-10-20 15:49:38 -07001886 // Set the current codecs to be used for the new channel. We need to do this
1887 // after adding the channel to send_channels_, because of how max bitrate is
1888 // currently being configured by SetSendCodec().
1889 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_)) {
1890 RemoveSendStream(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001891 return false;
1892 }
1893
1894 // At this point the channel's local SSRC has been updated. If the channel is
solenberg0a617e22015-10-20 15:49:38 -07001895 // the first send channel make sure that all the receive channels are updated
1896 // with the same SSRC in order to send receiver reports.
solenbergc96df772015-10-21 13:01:53 -07001897 if (send_streams_.size() == 1) {
solenberg0a617e22015-10-20 15:49:38 -07001898 receiver_reports_ssrc_ = ssrc;
solenberg7add0582015-11-20 09:59:34 -08001899 for (const auto& stream : recv_streams_) {
1900 int recv_channel = stream.second->channel();
solenberg0a617e22015-10-20 15:49:38 -07001901 if (engine()->voe()->rtp()->SetLocalSSRC(recv_channel, ssrc) != 0) {
solenberg7add0582015-11-20 09:59:34 -08001902 LOG_RTCERR2(SetLocalSSRC, recv_channel, ssrc);
solenberg1ac56142015-10-13 03:58:19 -07001903 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001904 }
solenberg0a617e22015-10-20 15:49:38 -07001905 engine()->voe()->base()->AssociateSendChannel(recv_channel, channel);
1906 LOG(LS_INFO) << "VoiceEngine channel #" << recv_channel
1907 << " is associated with channel #" << channel << ".";
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001908 }
1909 }
1910
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001911 return ChangeSend(channel, desired_send_);
1912}
1913
Peter Boström0c4e06b2015-10-07 12:23:21 +02001914bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
solenberg566ef242015-11-06 15:34:49 -08001915 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg3a941542015-11-16 07:34:50 -08001916 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1917
solenbergc96df772015-10-21 13:01:53 -07001918 auto it = send_streams_.find(ssrc);
1919 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001920 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1921 << " which doesn't exist.";
1922 return false;
1923 }
1924
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001925 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001926 ChangeSend(channel, SEND_NOTHING);
1927
solenberg7add0582015-11-20 09:59:34 -08001928 // Clean up and delete the send stream+channel.
solenberg0a617e22015-10-20 15:49:38 -07001929 LOG(LS_INFO) << "Removing audio send stream " << ssrc
1930 << " with VoiceEngine channel #" << channel << ".";
solenberg7add0582015-11-20 09:59:34 -08001931 delete it->second;
1932 send_streams_.erase(it);
1933 if (!DeleteVoEChannel(channel)) {
solenberg0a617e22015-10-20 15:49:38 -07001934 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001935 }
solenbergc96df772015-10-21 13:01:53 -07001936 if (send_streams_.empty()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001937 ChangeSend(SEND_NOTHING);
solenberg0a617e22015-10-20 15:49:38 -07001938 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939 return true;
1940}
1941
1942bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
solenberg566ef242015-11-06 15:34:49 -08001943 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07001944 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
1945
solenberg0b675462015-10-09 01:37:09 -07001946 if (!ValidateStreamParams(sp)) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001947 return false;
1948 }
1949
solenberg7add0582015-11-20 09:59:34 -08001950 const uint32_t ssrc = sp.first_ssrc();
solenberg0b675462015-10-09 01:37:09 -07001951 if (ssrc == 0) {
1952 LOG(LS_WARNING) << "AddRecvStream with ssrc==0 is not supported.";
1953 return false;
1954 }
1955
solenberg1ac56142015-10-13 03:58:19 -07001956 // Remove the default receive stream if one had been created with this ssrc;
1957 // we'll recreate it then.
1958 if (IsDefaultRecvStream(ssrc)) {
1959 RemoveRecvStream(ssrc);
1960 }
solenberg0b675462015-10-09 01:37:09 -07001961
solenberg7add0582015-11-20 09:59:34 -08001962 if (GetReceiveChannelId(ssrc) != -1) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001963 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 return false;
1965 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967 // Create a new channel for receiving audio data.
solenberg7add0582015-11-20 09:59:34 -08001968 const int channel = CreateVoEChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return false;
1971 }
Minyue2013aec2015-05-13 14:14:42 +02001972
solenberg1ac56142015-10-13 03:58:19 -07001973 // Turn off all supported codecs.
solenberg26c8c912015-11-27 04:00:25 -08001974 // TODO(solenberg): Remove once "no codecs" is the default state of a stream.
1975 for (webrtc::CodecInst voe_codec : webrtc::acm2::RentACodec::Database()) {
1976 voe_codec.pltype = -1;
1977 if (engine()->voe()->codec()->SetRecPayloadType(channel, voe_codec) == -1) {
1978 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
1979 DeleteVoEChannel(channel);
1980 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001981 }
1982 }
1983
solenberg1ac56142015-10-13 03:58:19 -07001984 // Only enable those configured for this channel.
1985 for (const auto& codec : recv_codecs_) {
1986 webrtc::CodecInst voe_codec;
solenberg26c8c912015-11-27 04:00:25 -08001987 if (WebRtcVoiceEngine::ToCodecInst(codec, &voe_codec)) {
solenberg1ac56142015-10-13 03:58:19 -07001988 voe_codec.pltype = codec.id;
1989 if (engine()->voe()->codec()->SetRecPayloadType(
1990 channel, voe_codec) == -1) {
1991 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
solenberg7add0582015-11-20 09:59:34 -08001992 DeleteVoEChannel(channel);
solenberg1ac56142015-10-13 03:58:19 -07001993 return false;
1994 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001995 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 }
solenberg8fb30c32015-10-13 03:06:58 -07001997
solenberg7add0582015-11-20 09:59:34 -08001998 const int send_channel = GetSendChannelId(receiver_reports_ssrc_);
1999 if (send_channel != -1) {
2000 // Associate receive channel with first send channel (so the receive channel
2001 // can obtain RTT from the send channel)
2002 engine()->voe()->base()->AssociateSendChannel(channel, send_channel);
2003 LOG(LS_INFO) << "VoiceEngine channel #" << channel
2004 << " is associated with channel #" << send_channel << ".";
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002005 }
2006
solenberg7add0582015-11-20 09:59:34 -08002007 recv_streams_.insert(std::make_pair(ssrc, new WebRtcAudioReceiveStream(
2008 channel, ssrc, receiver_reports_ssrc_,
2009 options_.combined_audio_video_bwe.value_or(false), sp.sync_label,
2010 recv_rtp_extensions_, call_)));
2011
2012 SetNack(channel, nack_enabled_);
solenberg1ac56142015-10-13 03:58:19 -07002013 SetPlayout(channel, playout_);
solenberg7add0582015-11-20 09:59:34 -08002014
solenberg1ac56142015-10-13 03:58:19 -07002015 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016}
2017
Peter Boström0c4e06b2015-10-07 12:23:21 +02002018bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
solenberg566ef242015-11-06 15:34:49 -08002019 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergd97ec302015-10-07 01:40:33 -07002020 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
2021
solenberg7add0582015-11-20 09:59:34 -08002022 const auto it = recv_streams_.find(ssrc);
2023 if (it == recv_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002024 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2025 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002026 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028
solenberg1ac56142015-10-13 03:58:19 -07002029 // Deregister default channel, if that's the one being destroyed.
2030 if (IsDefaultRecvStream(ssrc)) {
2031 default_recv_ssrc_ = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002033
solenberg7add0582015-11-20 09:59:34 -08002034 const int channel = it->second->channel();
2035
2036 // Clean up and delete the receive stream+channel.
2037 LOG(LS_INFO) << "Removing audio receive stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002038 << " with VoiceEngine channel #" << channel << ".";
Tommif888bb52015-12-12 01:37:01 +01002039 it->second->SetRawAudioSink(nullptr);
solenberg7add0582015-11-20 09:59:34 -08002040 delete it->second;
2041 recv_streams_.erase(it);
2042 return DeleteVoEChannel(channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043}
2044
Peter Boström0c4e06b2015-10-07 12:23:21 +02002045bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32_t ssrc,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002046 AudioRenderer* renderer) {
solenbergc96df772015-10-21 13:01:53 -07002047 auto it = send_streams_.find(ssrc);
2048 if (it == send_streams_.end()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002049 if (renderer) {
2050 // Return an error if trying to set a valid renderer with an invalid ssrc.
2051 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2052 return false;
2053 }
2054
2055 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002056 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002057 }
2058
solenberg1ac56142015-10-13 03:58:19 -07002059 if (renderer) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002060 it->second->Start(renderer);
solenberg1ac56142015-10-13 03:58:19 -07002061 } else {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002062 it->second->Stop();
solenberg1ac56142015-10-13 03:58:19 -07002063 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002064
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065 return true;
2066}
2067
2068bool WebRtcVoiceMediaChannel::GetActiveStreams(
2069 AudioInfo::StreamList* actives) {
solenberg566ef242015-11-06 15:34:49 -08002070 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002071 actives->clear();
solenberg7add0582015-11-20 09:59:34 -08002072 for (const auto& ch : recv_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002073 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002074 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002075 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 }
2077 }
2078 return true;
2079}
2080
2081int WebRtcVoiceMediaChannel::GetOutputLevel() {
solenberg566ef242015-11-06 15:34:49 -08002082 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002083 int highest = 0;
solenberg7add0582015-11-20 09:59:34 -08002084 for (const auto& ch : recv_streams_) {
solenberg8fb30c32015-10-13 03:06:58 -07002085 highest = std::max(GetOutputLevel(ch.second->channel()), highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002086 }
2087 return highest;
2088}
2089
2090int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2091 int ret;
2092 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2093 // In case of error, log the info and continue
2094 LOG_RTCERR0(TimeSinceLastTyping);
2095 ret = -1;
2096 } else {
2097 ret *= 1000; // We return ms, webrtc returns seconds.
2098 }
2099 return ret;
2100}
2101
2102void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2103 int cost_per_typing, int reporting_threshold, int penalty_decay,
2104 int type_event_delay) {
2105 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2106 time_window, cost_per_typing,
2107 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2108 // In case of error, log the info and continue
2109 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2110 cost_per_typing, reporting_threshold, penalty_decay,
2111 type_event_delay);
2112 }
2113}
2114
solenberg4bac9c52015-10-09 02:32:53 -07002115bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
solenberg566ef242015-11-06 15:34:49 -08002116 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg1ac56142015-10-13 03:58:19 -07002117 if (ssrc == 0) {
2118 default_recv_volume_ = volume;
2119 if (default_recv_ssrc_ == -1) {
2120 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 }
solenberg1ac56142015-10-13 03:58:19 -07002122 ssrc = static_cast<uint32_t>(default_recv_ssrc_);
2123 }
2124 int ch_id = GetReceiveChannelId(ssrc);
2125 if (ch_id < 0) {
2126 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2127 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 }
2129
solenberg1ac56142015-10-13 03:58:19 -07002130 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(ch_id,
2131 volume)) {
2132 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, volume);
2133 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 }
solenberg1ac56142015-10-13 03:58:19 -07002135 LOG(LS_INFO) << "SetOutputVolume to " << volume
2136 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 return true;
2138}
2139
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002141 return dtmf_payload_type_ ? true : false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142}
2143
solenberg1d63dd02015-12-02 12:35:09 -08002144bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc, int event,
2145 int duration) {
solenberg566ef242015-11-06 15:34:49 -08002146 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002147 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2148 if (!dtmf_payload_type_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 return false;
2150 }
2151
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002152 // Figure out which WebRtcAudioSendStream to send the event on.
2153 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2154 if (it == send_streams_.end()) {
2155 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
solenberg1d63dd02015-12-02 12:35:09 -08002156 return false;
2157 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002158 if (event < kMinTelephoneEventCode ||
2159 event > kMaxTelephoneEventCode) {
2160 LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
solenberg1d63dd02015-12-02 12:35:09 -08002161 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 }
Fredrik Solenbergb5727682015-12-04 15:22:19 +01002163 if (duration < kMinTelephoneEventDuration ||
2164 duration > kMaxTelephoneEventDuration) {
2165 LOG(LS_WARNING) << "DTMF event duration " << duration << " out of range.";
2166 return false;
2167 }
2168 return it->second->SendTelephoneEvent(*dtmf_payload_type_, event, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169}
2170
wu@webrtc.orga9890802013-12-13 00:21:03 +00002171void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002172 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002173 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002174
solenberg1ac56142015-10-13 03:58:19 -07002175 uint32_t ssrc = 0;
2176 if (!GetRtpSsrc(packet->data(), packet->size(), &ssrc)) {
2177 return;
2178 }
2179
solenberg7e63ef02015-11-20 00:19:43 -08002180 // If we don't have a default channel, and the SSRC is unknown, create a
2181 // default channel.
2182 if (default_recv_ssrc_ == -1 && GetReceiveChannelId(ssrc) == -1) {
solenberg1ac56142015-10-13 03:58:19 -07002183 StreamParams sp;
2184 sp.ssrcs.push_back(ssrc);
2185 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
2186 if (!AddRecvStream(sp)) {
2187 LOG(LS_WARNING) << "Could not create default receive stream.";
2188 return;
2189 }
2190 default_recv_ssrc_ = ssrc;
2191 SetOutputVolume(default_recv_ssrc_, default_recv_volume_);
2192 }
2193
2194 // Forward packet to Call. If the SSRC is unknown we'll return after this.
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002195 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2196 packet_time.not_before);
solenberg1ac56142015-10-13 03:58:19 -07002197 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2198 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2199 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2200 webrtc_packet_time);
2201 if (webrtc::PacketReceiver::DELIVERY_OK != delivery_result) {
solenberg7e63ef02015-11-20 00:19:43 -08002202 // If the SSRC is unknown here, route it to the default channel, if we have
2203 // one. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2204 if (default_recv_ssrc_ == -1) {
2205 return;
2206 } else {
2207 ssrc = default_recv_ssrc_;
2208 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 }
2210
solenberg1ac56142015-10-13 03:58:19 -07002211 // Find the channel to send this packet to. It must exist since webrtc::Call
2212 // was able to demux the packet.
2213 int channel = GetReceiveChannelId(ssrc);
2214 RTC_DCHECK(channel != -1);
2215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002217 engine()->voe()->network()->ReceivedRTPPacket(
solenberg1ac56142015-10-13 03:58:19 -07002218 channel, packet->data(), packet->size(), webrtc_packet_time);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219}
2220
wu@webrtc.orga9890802013-12-13 00:21:03 +00002221void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002222 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
solenberg566ef242015-11-06 15:34:49 -08002223 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002224
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002225 // Forward packet to Call as well.
2226 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2227 packet_time.not_before);
2228 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2229 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2230 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002231
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002232 // Sending channels need all RTCP packets with feedback information.
2233 // Even sender reports can contain attached report blocks.
2234 // Receiving channels need sender reports in order to create
2235 // correct receiver reports.
2236 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002237 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002238 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2239 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 }
2241
solenberg0b675462015-10-09 01:37:09 -07002242 // If it is a sender report, find the receive channel that is listening.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002243 if (type == kRtcpTypeSR) {
solenberg0b675462015-10-09 01:37:09 -07002244 uint32_t ssrc = 0;
2245 if (!GetRtcpSsrc(packet->data(), packet->size(), &ssrc)) {
2246 return;
2247 }
2248 int recv_channel_id = GetReceiveChannelId(ssrc);
2249 if (recv_channel_id != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002250 engine()->voe()->network()->ReceivedRTCPPacket(
solenberg0b675462015-10-09 01:37:09 -07002251 recv_channel_id, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002252 }
2253 }
2254
2255 // SR may continue RR and any RR entry may correspond to any one of the send
2256 // channels. So all RTCP packets must be forwarded all send channels. VoE
2257 // will filter out RR internally.
solenbergc96df772015-10-21 13:01:53 -07002258 for (const auto& ch : send_streams_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002259 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002260 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002261 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002262}
2263
Peter Boström0c4e06b2015-10-07 12:23:21 +02002264bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
solenberg566ef242015-11-06 15:34:49 -08002265 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg0a617e22015-10-20 15:49:38 -07002266 int channel = GetSendChannelId(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002267 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002268 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2269 return false;
2270 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002271 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2272 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 return false;
2274 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002275 // We set the AGC to mute state only when all the channels are muted.
2276 // This implementation is not ideal, instead we should signal the AGC when
2277 // the mic channel is muted/unmuted. We can't do it today because there
2278 // is no good way to know which stream is mapping to the mic channel.
2279 bool all_muted = muted;
solenbergc96df772015-10-21 13:01:53 -07002280 for (const auto& ch : send_streams_) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002281 if (!all_muted) {
2282 break;
2283 }
2284 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002285 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002286 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002287 return false;
2288 }
2289 }
2290
2291 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
solenberg0a617e22015-10-20 15:49:38 -07002292 if (ap) {
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002293 ap->set_output_will_be_muted(all_muted);
solenberg0a617e22015-10-20 15:49:38 -07002294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 return true;
2296}
2297
minyue@webrtc.org26236952014-10-29 02:27:08 +00002298// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2299// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002300bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002301 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
minyue@webrtc.org26236952014-10-29 02:27:08 +00002302 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002303}
2304
minyue@webrtc.org26236952014-10-29 02:27:08 +00002305bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2306 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002307
minyue@webrtc.org26236952014-10-29 02:27:08 +00002308 send_bitrate_setting_ = true;
2309 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002310
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002312 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002313 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002314 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 }
2316
minyue@webrtc.org26236952014-10-29 02:27:08 +00002317 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002318 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2319 // SetMaxSendBandwith(0), the second call removes the previous limit.
2320 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002321 return true;
2322
2323 webrtc::CodecInst codec = *send_codec_;
solenberg26c8c912015-11-27 04:00:25 -08002324 bool is_multi_rate = WebRtcVoiceCodecs::IsCodecMultiRate(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002325
2326 if (is_multi_rate) {
2327 // If codec is multi-rate then just set the bitrate.
2328 codec.rate = bps;
solenbergc96df772015-10-21 13:01:53 -07002329 for (const auto& ch : send_streams_) {
solenberg0a617e22015-10-20 15:49:38 -07002330 if (!SetSendCodec(ch.second->channel(), codec)) {
2331 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2332 << " to bitrate " << bps << " bps.";
2333 return false;
2334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 }
2336 return true;
2337 } else {
2338 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2339 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2340 // fixed bitrate then ignore.
2341 if (bps < codec.rate) {
2342 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2343 << " to bitrate " << bps << " bps"
2344 << ", requires at least " << codec.rate << " bps.";
2345 return false;
2346 }
2347 return true;
2348 }
2349}
2350
2351bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
solenberg566ef242015-11-06 15:34:49 -08002352 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -07002353 RTC_DCHECK(info);
solenbergd97ec302015-10-07 01:40:33 -07002354
solenberg85a04962015-10-27 03:35:21 -07002355 // Get SSRC and stats for each sender.
2356 RTC_DCHECK(info->senders.size() == 0);
2357 for (const auto& stream : send_streams_) {
2358 webrtc::AudioSendStream::Stats stats = stream.second->GetStats();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002359 VoiceSenderInfo sinfo;
solenberg85a04962015-10-27 03:35:21 -07002360 sinfo.add_ssrc(stats.local_ssrc);
2361 sinfo.bytes_sent = stats.bytes_sent;
2362 sinfo.packets_sent = stats.packets_sent;
2363 sinfo.packets_lost = stats.packets_lost;
2364 sinfo.fraction_lost = stats.fraction_lost;
2365 sinfo.codec_name = stats.codec_name;
2366 sinfo.ext_seqnum = stats.ext_seqnum;
2367 sinfo.jitter_ms = stats.jitter_ms;
2368 sinfo.rtt_ms = stats.rtt_ms;
2369 sinfo.audio_level = stats.audio_level;
2370 sinfo.aec_quality_min = stats.aec_quality_min;
2371 sinfo.echo_delay_median_ms = stats.echo_delay_median_ms;
2372 sinfo.echo_delay_std_ms = stats.echo_delay_std_ms;
2373 sinfo.echo_return_loss = stats.echo_return_loss;
2374 sinfo.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
solenberg566ef242015-11-06 15:34:49 -08002375 sinfo.typing_noise_detected =
2376 (send_ == SEND_NOTHING ? false : stats.typing_noise_detected);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002377 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 }
2379
solenberg85a04962015-10-27 03:35:21 -07002380 // Get SSRC and stats for each receiver.
2381 RTC_DCHECK(info->receivers.size() == 0);
solenberg7add0582015-11-20 09:59:34 -08002382 for (const auto& stream : recv_streams_) {
Fredrik Solenberg4f4ec0a2015-10-22 10:49:27 +02002383 webrtc::AudioReceiveStream::Stats stats = stream.second->GetStats();
2384 VoiceReceiverInfo rinfo;
2385 rinfo.add_ssrc(stats.remote_ssrc);
2386 rinfo.bytes_rcvd = stats.bytes_rcvd;
2387 rinfo.packets_rcvd = stats.packets_rcvd;
2388 rinfo.packets_lost = stats.packets_lost;
2389 rinfo.fraction_lost = stats.fraction_lost;
2390 rinfo.codec_name = stats.codec_name;
2391 rinfo.ext_seqnum = stats.ext_seqnum;
2392 rinfo.jitter_ms = stats.jitter_ms;
2393 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2394 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2395 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2396 rinfo.audio_level = stats.audio_level;
2397 rinfo.expand_rate = stats.expand_rate;
2398 rinfo.speech_expand_rate = stats.speech_expand_rate;
2399 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2400 rinfo.accelerate_rate = stats.accelerate_rate;
2401 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2402 rinfo.decoding_calls_to_silence_generator =
2403 stats.decoding_calls_to_silence_generator;
2404 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2405 rinfo.decoding_normal = stats.decoding_normal;
2406 rinfo.decoding_plc = stats.decoding_plc;
2407 rinfo.decoding_cng = stats.decoding_cng;
2408 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2409 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2410 info->receivers.push_back(rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 }
2412
2413 return true;
2414}
2415
Tommif888bb52015-12-12 01:37:01 +01002416void WebRtcVoiceMediaChannel::SetRawAudioSink(
2417 uint32_t ssrc,
deadbeef2d110be2016-01-13 12:00:26 -08002418 rtc::scoped_ptr<webrtc::AudioSinkInterface> sink) {
Tommif888bb52015-12-12 01:37:01 +01002419 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
2420 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink";
2421 const auto it = recv_streams_.find(ssrc);
2422 if (it == recv_streams_.end()) {
2423 LOG(LS_WARNING) << "SetRawAudioSink: no recv stream" << ssrc;
2424 return;
2425 }
deadbeef2d110be2016-01-13 12:00:26 -08002426 it->second->SetRawAudioSink(std::move(sink));
Tommif888bb52015-12-12 01:37:01 +01002427}
2428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002429int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
solenbergd97ec302015-10-07 01:40:33 -07002430 unsigned int ulevel = 0;
2431 int ret = engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002432 return (ret == 0) ? static_cast<int>(ulevel) : -1;
2433}
2434
Peter Boström0c4e06b2015-10-07 12:23:21 +02002435int WebRtcVoiceMediaChannel::GetReceiveChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002436 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg7add0582015-11-20 09:59:34 -08002437 const auto it = recv_streams_.find(ssrc);
2438 if (it != recv_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002439 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002440 }
solenberg1ac56142015-10-13 03:58:19 -07002441 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442}
2443
Peter Boström0c4e06b2015-10-07 12:23:21 +02002444int WebRtcVoiceMediaChannel::GetSendChannelId(uint32_t ssrc) const {
solenberg566ef242015-11-06 15:34:49 -08002445 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergc96df772015-10-21 13:01:53 -07002446 const auto it = send_streams_.find(ssrc);
2447 if (it != send_streams_.end()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002448 return it->second->channel();
solenberg8fb30c32015-10-13 03:06:58 -07002449 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451}
2452
2453bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
2454 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
2455 // Get the RED encodings from the parameter with no name. This may
2456 // change based on what is discussed on the Jingle list.
2457 // The encoding parameter is of the form "a/b"; we only support where
2458 // a == b. Verify this and parse out the value into red_pt.
2459 // If the parameter value is absent (as it will be until we wire up the
2460 // signaling of this message), use the second codec specified (i.e. the
2461 // one after "red") as the encoding parameter.
2462 int red_pt = -1;
2463 std::string red_params;
2464 CodecParameterMap::const_iterator it = red_codec.params.find("");
2465 if (it != red_codec.params.end()) {
2466 red_params = it->second;
2467 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002468 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002470 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
2472 return false;
2473 }
2474 } else if (red_codec.params.empty()) {
2475 LOG(LS_WARNING) << "RED params not present, using defaults";
2476 if (all_codecs.size() > 1) {
2477 red_pt = all_codecs[1].id;
2478 }
2479 }
2480
2481 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002482 for (const AudioCodec& codec : all_codecs) {
2483 if (codec.id == red_pt) {
2484 // If we find the right codec, that will be the codec we pass to
2485 // SetSendCodec, with the desired payload type.
solenberg26c8c912015-11-27 04:00:25 -08002486 if (WebRtcVoiceEngine::ToCodecInst(codec, send_codec)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002487 return true;
2488 } else {
2489 break;
2490 }
2491 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002493 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
2494 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495}
2496
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
2498 if (playout) {
2499 LOG(LS_INFO) << "Starting playout for channel #" << channel;
2500 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
2501 LOG_RTCERR1(StartPlayout, channel);
2502 return false;
2503 }
2504 } else {
2505 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
2506 engine()->voe()->base()->StopPlayout(channel);
2507 }
2508 return true;
2509}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002510} // namespace cricket
2511
2512#endif // HAVE_WEBRTC_VOICE