blob: fcf8ef754ff009ff575374abd3bdb81d873d4a20 [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"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000056#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
58#ifdef WIN32
59#include <objbase.h> // NOLINT
60#endif
61
62namespace cricket {
63
Brave Yao5225dd82015-03-26 07:39:19 +080064static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065struct CodecPref {
66 const char* name;
67 int clockrate;
68 int channels;
69 int payload_type;
70 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080071 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
Brave Yao5225dd82015-03-26 07:39:19 +080073// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080075 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
76 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
77 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000078 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080079 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
80 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
81 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
82 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080083 { kCnCodecName, 32000, 1, 106, false, { } },
84 { kCnCodecName, 16000, 1, 105, false, { } },
85 { kCnCodecName, 8000, 1, 13, false, { } },
86 { kRedCodecName, 8000, 1, 127, false, { } },
87 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088};
89
90// For Linux/Mac, using the default device is done by specifying index 0 for
91// VoE 4.0 and not -1 (which was the case for VoE 3.5).
92//
93// On Windows Vista and newer, Microsoft introduced the concept of "Default
94// Communications Device". This means that there are two types of default
95// devices (old Wave Audio style default and Default Communications Device).
96//
97// On Windows systems which only support Wave Audio style default, uses either
98// -1 or 0 to select the default device.
99//
100// On Windows systems which support both "Default Communication Device" and
101// old Wave Audio style default, use -1 for Default Communications Device and
102// -2 for Wave Audio style default, which is what we want to use for clips.
103// It's not clear yet whether the -2 index is handled properly on other OSes.
104
105#ifdef WIN32
106static const int kDefaultAudioDeviceId = -1;
107static const int kDefaultSoundclipDeviceId = -2;
108#else
109static const int kDefaultAudioDeviceId = 0;
110#endif
111
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112// Parameter used for NACK.
113// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
114static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000115
116// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000117// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000118
119// Recommended bitrates:
120// 8-12 kb/s for NB speech,
121// 16-20 kb/s for WB speech,
122// 28-40 kb/s for FB speech,
123// 48-64 kb/s for FB mono music, and
124// 64-128 kb/s for FB stereo music.
125// The current implementation applies the following values to mono signals,
126// and multiplies them by 2 for stereo.
127static const int kOpusBitrateNb = 12000;
128static const int kOpusBitrateWb = 20000;
129static const int kOpusBitrateFb = 32000;
130
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000131// Opus bitrate should be in the range between 6000 and 510000.
132static const int kOpusMinBitrate = 6000;
133static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000134
wu@webrtc.orgde305012013-10-31 15:40:38 +0000135// Default audio dscp value.
136// See http://tools.ietf.org/html/rfc2474 for details.
137// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000138static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000139
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// Ensure we open the file in a writeable path on ChromeOS and Android. This
141// workaround can be removed when it's possible to specify a filename for audio
142// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143//
144// TODO(grunell): Use a string in the options instead of hardcoding it here
145// and let the embedder choose the filename (crbug.com/264223).
146//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000147// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
148// below.
149#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000150static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000151#elif defined(ANDROID)
152static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000153#else
154static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
155#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000156
157// Dumps an AudioCodec in RFC 2327-ish format.
158static std::string ToString(const AudioCodec& codec) {
159 std::stringstream ss;
160 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
161 << " (" << codec.id << ")";
162 return ss.str();
163}
Minyue Li7100dcd2015-03-27 05:05:59 +0100164
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165static std::string ToString(const webrtc::CodecInst& codec) {
166 std::stringstream ss;
167 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
168 << " (" << codec.pltype << ")";
169 return ss.str();
170}
171
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000172static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000173 const char* delim = "\r\n";
174 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
175 LOG_V(sev) << tok;
176 }
177}
178
179// Severity is an integer because it comes is assumed to be from command line.
180static int SeverityToFilter(int severity) {
181 int filter = webrtc::kTraceNone;
182 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200185 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200188 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000189 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200191 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000192 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
194 }
195 return filter;
196}
197
Minyue Li7100dcd2015-03-27 05:05:59 +0100198static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
199 return (_stricmp(codec.name.c_str(), ref_name) == 0);
200}
201
202static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
203 return (_stricmp(codec.plname, ref_name) == 0);
204}
205
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000206static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
207 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100208 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209 kCodecPrefs[i].clockrate == codec.plfreq) {
210 return kCodecPrefs[i].is_multi_rate;
211 }
212 }
213 return false;
214}
215
216static bool FindCodec(const std::vector<AudioCodec>& codecs,
217 const AudioCodec& codec,
218 AudioCodec* found_codec) {
219 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
220 it != codecs.end(); ++it) {
221 if (it->Matches(codec)) {
222 if (found_codec != NULL) {
223 *found_codec = *it;
224 }
225 return true;
226 }
227 }
228 return false;
229}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000230
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231static bool IsNackEnabled(const AudioCodec& codec) {
232 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
233 kParamValueEmpty));
234}
235
Brave Yao5225dd82015-03-26 07:39:19 +0800236static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
237 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
238 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
239 if (packet_size_ms && packet_size_ms <= ptime_ms) {
240 selected_packet_size_ms = packet_size_ms;
241 }
242 }
243 return selected_packet_size_ms;
244}
245
246// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
247// pacsize if it's valid, or we will pick the next smallest value we support.
248// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
249static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
250 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100251 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800252 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100253 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800254 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
255 if (packet_size_ms) {
256 // Convert unit from milli-seconds to samples.
257 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
258 return true;
259 }
260 }
261 }
262 return false;
263}
264
Minyue Li7100dcd2015-03-27 05:05:59 +0100265// Return true if codec.params[feature] == "1", false otherwise.
266static bool IsCodecFeatureEnabled(const AudioCodec& codec,
267 const char* feature) {
268 int value;
269 return codec.GetParam(feature, &value) && value == 1;
270}
271
272// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
273// otherwise. If the value (either from params or codec.bitrate) <=0, use the
274// default configuration. If the value is beyond feasible bit rate of Opus,
275// clamp it. Returns the Opus bit rate for operation.
276static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
277 int bitrate = 0;
278 bool use_param = true;
279 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
280 bitrate = codec.bitrate;
281 use_param = false;
282 }
283 if (bitrate <= 0) {
284 if (max_playback_rate <= 8000) {
285 bitrate = kOpusBitrateNb;
286 } else if (max_playback_rate <= 16000) {
287 bitrate = kOpusBitrateWb;
288 } else {
289 bitrate = kOpusBitrateFb;
290 }
291
292 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
293 bitrate *= 2;
294 }
295 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
296 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
297 std::string rate_source =
298 use_param ? "Codec parameter \"maxaveragebitrate\"" :
299 "Supplied Opus bitrate";
300 LOG(LS_WARNING) << rate_source
301 << " is invalid and is replaced by: "
302 << bitrate;
303 }
304 return bitrate;
305}
306
307// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
308// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
309static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
310 int value;
311 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
312 return value;
313 }
314 return kOpusDefaultMaxPlaybackRate;
315}
316
317static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
318 bool* enable_codec_fec, int* max_playback_rate,
319 bool* enable_codec_dtx) {
320 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
321 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
322 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
323
324 // If OPUS, change what we send according to the "stereo" codec
325 // parameter, and not the "channels" parameter. We set
326 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
327 // the bitrate is not specified, i.e. is <= zero, we set it to the
328 // appropriate default value for mono or stereo Opus.
329
330 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
331 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
332}
333
334// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
335// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
336// codec.
337static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
338 if (IsCodec(*voe_codec, kG722CodecName)) {
339 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
340 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200341 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100342 voe_codec->plfreq = new_plfreq;
343 }
344}
345
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000346// Gets the default set of options applied to the engine. Historically, these
347// were supplied as a combination of flags from the channel manager (ec, agc,
348// ns, and highpass) and the rest hardcoded in InitInternal.
349static AudioOptions GetDefaultEngineOptions() {
350 AudioOptions options;
351 options.echo_cancellation.Set(true);
352 options.auto_gain_control.Set(true);
353 options.noise_suppression.Set(true);
354 options.highpass_filter.Set(true);
355 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200356 options.audio_jitter_buffer_max_packets.Set(50);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000357 options.typing_detection.Set(true);
358 options.conference_mode.Set(false);
359 options.adjust_agc_delta.Set(0);
360 options.experimental_agc.Set(false);
361 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100362 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000363 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000364 options.aec_dump.Set(false);
365 return options;
366}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000367
Minyue Li7100dcd2015-03-27 05:05:59 +0100368static std::string GetEnableString(bool enable) {
369 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800370}
371
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372class WebRtcSoundclipMedia : public SoundclipMedia {
373 public:
374 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
375 : engine_(engine), webrtc_channel_(-1) {
376 engine_->RegisterSoundclip(this);
377 }
378
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +0200379 ~WebRtcSoundclipMedia() override {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000380 engine_->UnregisterSoundclip(this);
381 if (webrtc_channel_ != -1) {
382 // We shouldn't have to call Disable() here. DeleteChannel() should call
383 // StopPlayout() while deleting the channel. We should fix the bug
384 // inside WebRTC and remove the Disable() call bellow. This work is
385 // tracked by bug http://b/issue?id=5382855.
386 PlaySound(NULL, 0, 0);
387 Disable();
388 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
389 == -1) {
390 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
391 }
392 }
393 }
394
395 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000396 if (!engine_->voe_sc()) {
397 return false;
398 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000399 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400 if (webrtc_channel_ == -1) {
401 LOG_RTCERR0(CreateChannel);
402 return false;
403 }
404 return true;
405 }
406
407 bool Enable() {
408 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
409 LOG_RTCERR1(StartPlayout, webrtc_channel_);
410 return false;
411 }
412 return true;
413 }
414
415 bool Disable() {
416 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
417 LOG_RTCERR1(StopPlayout, webrtc_channel_);
418 return false;
419 }
420 return true;
421 }
422
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +0200423 bool PlaySound(const char* buf, int len, int flags) override {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000424 // The voe file api is not available in chrome.
425 if (!engine_->voe_sc()->file()) {
426 return false;
427 }
428 // Must stop playing the current sound (if any), because we are about to
429 // modify the stream.
430 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
431 == -1) {
432 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
433 return false;
434 }
435
436 if (buf) {
437 stream_.reset(new WebRtcSoundclipStream(buf, len));
438 stream_->set_loop((flags & SF_LOOP) != 0);
439 stream_->Rewind();
440
441 // Play it.
442 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
443 webrtc_channel_, stream_.get()) == -1) {
444 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
445 LOG(LS_ERROR) << "Unable to start soundclip";
446 return false;
447 }
448 } else {
449 stream_.reset();
450 }
451 return true;
452 }
453
454 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
455
456 private:
457 WebRtcVoiceEngine *engine_;
458 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000459 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000460};
461
462WebRtcVoiceEngine::WebRtcVoiceEngine()
463 : voe_wrapper_(new VoEWrapper()),
464 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000465 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466 tracing_(new VoETraceWrapper()),
467 adm_(NULL),
468 adm_sc_(NULL),
469 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
470 is_dumping_aec_(false),
471 desired_local_monitor_enable_(false),
472 tx_processor_ssrc_(0),
473 rx_processor_ssrc_(0) {
474 Construct();
475}
476
477WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
478 VoEWrapper* voe_wrapper_sc,
479 VoETraceWrapper* tracing)
480 : voe_wrapper_(voe_wrapper),
481 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000482 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000483 tracing_(tracing),
484 adm_(NULL),
485 adm_sc_(NULL),
486 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
487 is_dumping_aec_(false),
488 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000489 tx_processor_ssrc_(0),
490 rx_processor_ssrc_(0) {
491 Construct();
492}
493
494void WebRtcVoiceEngine::Construct() {
495 SetTraceFilter(log_filter_);
496 initialized_ = false;
497 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
498 SetTraceOptions("");
499 if (tracing_->SetTraceCallback(this) == -1) {
500 LOG_RTCERR0(SetTraceCallback);
501 }
502 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
503 LOG_RTCERR0(RegisterVoiceEngineObserver);
504 }
505 // Clear the default agc state.
506 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
507
508 // Load our audio codec list.
509 ConstructCodecs();
510
511 // Load our RTP Header extensions.
512 rtp_header_extensions_.push_back(
513 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
514 kRtpAudioLevelHeaderExtensionDefaultId));
515 rtp_header_extensions_.push_back(
516 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
517 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
518 options_ = GetDefaultEngineOptions();
519}
520
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000521void WebRtcVoiceEngine::ConstructCodecs() {
522 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
523 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
524 for (int i = 0; i < ncodecs; ++i) {
525 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000526 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000527 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100528 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000529 continue;
530 }
531
532 const CodecPref* pref = NULL;
533 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100534 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000535 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
536 kCodecPrefs[j].channels == voe_codec.channels) {
537 pref = &kCodecPrefs[j];
538 break;
539 }
540 }
541
542 if (pref) {
543 // Use the payload type that we've configured in our pref table;
544 // use the offset in our pref table to determine the sort order.
545 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
546 voe_codec.rate, voe_codec.channels,
547 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
548 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100549 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000550 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000551 codec.bitrate = 0;
552 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100553 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000554 // Only add fmtp parameters that differ from the spec.
555 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
556 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000557 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000558 }
559 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
560 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000561 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000562 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000563 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000564
565 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000566 // when they can be set to values other than the default.
567 }
568 codecs_.push_back(codec);
569 } else {
570 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
571 }
572 }
573 }
574 // Make sure they are in local preference order.
575 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
576}
577
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000578bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
579 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
580 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000581 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000582 // Change the sample rate of G722 to 8000 to match SDP.
583 MaybeFixupG722(codec, 8000);
584 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000585}
586
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000587WebRtcVoiceEngine::~WebRtcVoiceEngine() {
588 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
589 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
590 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
591 }
592 if (adm_) {
593 voe_wrapper_.reset();
594 adm_->Release();
595 adm_ = NULL;
596 }
597 if (adm_sc_) {
598 voe_wrapper_sc_.reset();
599 adm_sc_->Release();
600 adm_sc_ = NULL;
601 }
602
603 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200604 DCHECK(SignalRxMediaFrame.is_empty());
605 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000606
607 tracing_->SetTraceCallback(NULL);
608}
609
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000610bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200611 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000612 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
613 bool res = InitInternal();
614 if (res) {
615 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
616 } else {
617 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
618 Terminate();
619 }
620 return res;
621}
622
623bool WebRtcVoiceEngine::InitInternal() {
624 // Temporarily turn logging level up for the Init call
625 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000626 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000627 SetTraceFilter(extended_filter);
628 SetTraceOptions("");
629
630 // Init WebRtc VoiceEngine.
631 if (voe_wrapper_->base()->Init(adm_) == -1) {
632 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
633 SetTraceFilter(old_filter);
634 return false;
635 }
636
637 SetTraceFilter(old_filter);
638 SetTraceOptions(log_options_);
639
640 // Log the VoiceEngine version info
641 char buffer[1024] = "";
642 voe_wrapper_->base()->GetVersion(buffer);
643 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000644 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000645
646 // Save the default AGC configuration settings. This must happen before
647 // calling SetOptions or the default will be overwritten.
648 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
649 LOG_RTCERR0(GetAgcConfig);
650 return false;
651 }
652
653 // Set defaults for options, so that ApplyOptions applies them explicitly
654 // when we clear option (channel) overrides. External clients can still
655 // modify the defaults via SetOptions (on the media engine).
656 if (!SetOptions(GetDefaultEngineOptions())) {
657 return false;
658 }
659
660 // Print our codec list again for the call diagnostic log
661 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
662 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
663 it != codecs_.end(); ++it) {
664 LOG(LS_INFO) << ToString(*it);
665 }
666
667 // Disable the DTMF playout when a tone is sent.
668 // PlayDtmfTone will be used if local playout is needed.
669 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
670 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
671 }
672
673 initialized_ = true;
674 return true;
675}
676
677bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
678 if (voe_wrapper_sc_initialized_) {
679 return true;
680 }
681 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
682 // be false, so subsequent calls to EnsureSoundclipEngineInit will
683 // probably just fail again. That's acceptable behavior.
684#if defined(LINUX) && !defined(HAVE_LIBPULSE)
685 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
686#endif
687
688 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
689 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
690 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
691 return false;
692 }
693
694 // On Windows, tell it to use the default sound (not communication) devices.
695 // First check whether there is a valid sound device for playback.
696 // TODO(juberti): Clean this up when we support setting the soundclip device.
697#ifdef WIN32
698 // The SetPlayoutDevice may not be implemented in the case of external ADM.
699 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
700 // PeerConnection interface never set the adm_sc_, so need to check both
701 // in order to determine if the external adm is used.
702 if (!adm_ && !adm_sc_) {
703 int num_of_devices = 0;
704 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
705 num_of_devices > 0) {
706 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
707 == -1) {
708 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
709 voe_wrapper_sc_->error());
710 return false;
711 }
712 } else {
713 LOG(LS_WARNING) << "No valid sound playout device found.";
714 }
715 }
716#endif
717 voe_wrapper_sc_initialized_ = true;
718 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
719 return true;
720}
721
722void WebRtcVoiceEngine::Terminate() {
723 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
724 initialized_ = false;
725
726 StopAecDump();
727
728 if (voe_wrapper_sc_) {
729 voe_wrapper_sc_initialized_ = false;
730 voe_wrapper_sc_->base()->Terminate();
731 }
732 voe_wrapper_->base()->Terminate();
733 desired_local_monitor_enable_ = false;
734}
735
736int WebRtcVoiceEngine::GetCapabilities() {
737 return AUDIO_SEND | AUDIO_RECV;
738}
739
740VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
741 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
742 if (!ch->valid()) {
743 delete ch;
744 ch = NULL;
745 }
746 return ch;
747}
748
749SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
750 if (!EnsureSoundclipEngineInit()) {
751 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
752 << "initialize.";
753 return NULL;
754 }
755 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
756 if (!soundclip->Init() || !soundclip->Enable()) {
757 delete soundclip;
758 return NULL;
759 }
760 return soundclip;
761}
762
763bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
764 if (!ApplyOptions(options)) {
765 return false;
766 }
767 options_ = options;
768 return true;
769}
770
771bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
772 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
773 if (!ApplyOptions(overrides)) {
774 return false;
775 }
776 option_overrides_ = overrides;
777 return true;
778}
779
780bool WebRtcVoiceEngine::ClearOptionOverrides() {
781 LOG(LS_INFO) << "Clearing option overrides.";
782 AudioOptions options = options_;
783 // Only call ApplyOptions if |options_overrides_| contains overrided options.
784 // ApplyOptions affects NS, AGC other options that is shared between
785 // all WebRtcVoiceEngineChannels.
786 if (option_overrides_ == AudioOptions()) {
787 return true;
788 }
789
790 if (!ApplyOptions(options)) {
791 return false;
792 }
793 option_overrides_ = AudioOptions();
794 return true;
795}
796
797// AudioOptions defaults are set in InitInternal (for options with corresponding
798// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
799bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
800 AudioOptions options = options_in; // The options are modified below.
801 // kEcConference is AEC with high suppression.
802 webrtc::EcModes ec_mode = webrtc::kEcConference;
803 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
804 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
805 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
806 bool aecm_comfort_noise = false;
807 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
808 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
809 << aecm_comfort_noise << " (default is false).";
810 }
811
812#if defined(IOS)
813 // On iOS, VPIO provides built-in EC and AGC.
814 options.echo_cancellation.Set(false);
815 options.auto_gain_control.Set(false);
816#elif defined(ANDROID)
817 ec_mode = webrtc::kEcAecm;
818#endif
819
820#if defined(IOS) || defined(ANDROID)
821 // Set the AGC mode for iOS as well despite disabling it above, to avoid
822 // unsupported configuration errors from webrtc.
823 agc_mode = webrtc::kAgcFixedDigital;
824 options.typing_detection.Set(false);
825 options.experimental_agc.Set(false);
826 options.experimental_aec.Set(false);
827 options.experimental_ns.Set(false);
828#endif
829
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100830 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
831 // where the feature is not supported.
832 bool use_delay_agnostic_aec = false;
833#if !defined(IOS)
834 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
835 if (use_delay_agnostic_aec) {
836 options.echo_cancellation.Set(true);
837 options.experimental_aec.Set(true);
838 ec_mode = webrtc::kEcConference;
839 }
840 }
841#endif
842
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000843 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
844
845 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
846
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000847 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000848 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000849 // Check if platform supports built-in EC. Currently only supported on
850 // Android and in combination with Java based audio layer.
851 // TODO(henrika): investigate possibility to support built-in EC also
852 // in combination with Open SL ES audio.
853 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200854 if (built_in_aec && !use_delay_agnostic_aec) {
855 // Built-in EC exists on this device and use_delay_agnostic_aec is not
856 // overriding it. Enable/Disable it according to the echo_cancellation
857 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200858 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
859 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100860 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000861 // i.e., replace the software EC with the built-in EC.
862 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000863 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000864 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
865 }
866 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000867 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
868 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
869 return false;
870 } else {
871 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
872 << " with mode " << ec_mode;
873 }
874#if !defined(ANDROID)
875 // TODO(ajm): Remove the error return on Android from webrtc.
876 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
877 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
878 return false;
879 }
880#endif
881 if (ec_mode == webrtc::kEcAecm) {
882 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
883 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
884 return false;
885 }
886 }
887 }
888
889 bool auto_gain_control;
890 if (options.auto_gain_control.Get(&auto_gain_control)) {
891 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
892 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
893 return false;
894 } else {
895 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
896 << " with mode " << agc_mode;
897 }
898 }
899
900 if (options.tx_agc_target_dbov.IsSet() ||
901 options.tx_agc_digital_compression_gain.IsSet() ||
902 options.tx_agc_limiter.IsSet()) {
903 // Override default_agc_config_. Generally, an unset option means "leave
904 // the VoE bits alone" in this function, so we want whatever is set to be
905 // stored as the new "default". If we didn't, then setting e.g.
906 // tx_agc_target_dbov would reset digital compression gain and limiter
907 // settings.
908 // Also, if we don't update default_agc_config_, then adjust_agc_delta
909 // would be an offset from the original values, and not whatever was set
910 // explicitly.
911 default_agc_config_.targetLeveldBOv =
912 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
913 default_agc_config_.targetLeveldBOv);
914 default_agc_config_.digitalCompressionGaindB =
915 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
916 default_agc_config_.digitalCompressionGaindB);
917 default_agc_config_.limiterEnable =
918 options.tx_agc_limiter.GetWithDefaultIfUnset(
919 default_agc_config_.limiterEnable);
920 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
921 LOG_RTCERR3(SetAgcConfig,
922 default_agc_config_.targetLeveldBOv,
923 default_agc_config_.digitalCompressionGaindB,
924 default_agc_config_.limiterEnable);
925 return false;
926 }
927 }
928
929 bool noise_suppression;
930 if (options.noise_suppression.Get(&noise_suppression)) {
931 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
932 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
933 return false;
934 } else {
935 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
936 << " with mode " << ns_mode;
937 }
938 }
939
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000940 bool highpass_filter;
941 if (options.highpass_filter.Get(&highpass_filter)) {
942 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
943 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
944 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
945 return false;
946 }
947 }
948
949 bool stereo_swapping;
950 if (options.stereo_swapping.Get(&stereo_swapping)) {
951 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
952 voep->EnableStereoChannelSwapping(stereo_swapping);
953 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
954 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
955 return false;
956 }
957 }
958
Henrik Lundin64dad832015-05-11 12:44:23 +0200959 int audio_jitter_buffer_max_packets;
960 if (options.audio_jitter_buffer_max_packets.Get(
961 &audio_jitter_buffer_max_packets)) {
962 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
963 voe_config_.Set<webrtc::NetEqCapacityConfig>(
964 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
965 }
966
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000967 bool typing_detection;
968 if (options.typing_detection.Get(&typing_detection)) {
969 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
970 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
971 // In case of error, log the info and continue
972 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
973 }
974 }
975
976 int adjust_agc_delta;
977 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
978 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
979 if (!AdjustAgcLevel(adjust_agc_delta)) {
980 return false;
981 }
982 }
983
984 bool aec_dump;
985 if (options.aec_dump.Get(&aec_dump)) {
986 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
987 if (aec_dump)
988 StartAecDump(kAecDumpByAudioOptionFilename);
989 else
990 StopAecDump();
991 }
992
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000993 webrtc::Config config;
994
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100995 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
996 bool delay_agnostic_aec;
997 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
998 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
999 config.Set<webrtc::ReportedDelay>(
1000 new webrtc::ReportedDelay(!delay_agnostic_aec));
1001 }
1002
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001003 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001004 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001005 if (experimental_aec_.Get(&experimental_aec)) {
1006 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
1007 config.Set<webrtc::DelayCorrection>(
1008 new webrtc::DelayCorrection(experimental_aec));
1009 }
1010
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001011 experimental_ns_.SetFrom(options.experimental_ns);
1012 bool experimental_ns;
1013 if (experimental_ns_.Get(&experimental_ns)) {
1014 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
1015 config.Set<webrtc::ExperimentalNs>(
1016 new webrtc::ExperimentalNs(experimental_ns));
1017 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001018
1019 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
1020 // returns NULL on audio_processing().
1021 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
1022 if (audioproc) {
1023 audioproc->SetExtraOptions(config);
1024 }
1025
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001026 uint32 recording_sample_rate;
1027 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1028 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1029 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1030 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1031 }
1032 }
1033
1034 uint32 playout_sample_rate;
1035 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1036 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1037 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1038 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1039 }
1040 }
1041
1042 return true;
1043}
1044
1045bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1046 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1047 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1048 LOG_RTCERR1(SetDelayOffsetMs, offset);
1049 return false;
1050 }
1051
1052 return true;
1053}
1054
1055struct ResumeEntry {
1056 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1057 : channel(c),
1058 playout(p),
1059 send(s) {
1060 }
1061
1062 WebRtcVoiceMediaChannel *channel;
1063 bool playout;
1064 SendFlags send;
1065};
1066
1067// TODO(juberti): Refactor this so that the core logic can be used to set the
1068// soundclip device. At that time, reinstate the soundclip pause/resume code.
1069bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1070 const Device* out_device) {
1071#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001072 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001073 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001074 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001075 kDefaultAudioDeviceId;
1076 // The device manager uses -1 as the default device, which was the case for
1077 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1078#ifndef WIN32
1079 if (-1 == in_id) {
1080 in_id = kDefaultAudioDeviceId;
1081 }
1082 if (-1 == out_id) {
1083 out_id = kDefaultAudioDeviceId;
1084 }
1085#endif
1086
1087 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1088 in_device->name : "Default device";
1089 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1090 out_device->name : "Default device";
1091 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1092 << ") and speaker to (id=" << out_id << ", name=" << out_name
1093 << ")";
1094
1095 // If we're running the local monitor, we need to stop it first.
1096 bool ret = true;
1097 if (!PauseLocalMonitor()) {
1098 LOG(LS_WARNING) << "Failed to pause local monitor";
1099 ret = false;
1100 }
1101
1102 // Must also pause all audio playback and capture.
1103 for (ChannelList::const_iterator i = channels_.begin();
1104 i != channels_.end(); ++i) {
1105 WebRtcVoiceMediaChannel *channel = *i;
1106 if (!channel->PausePlayout()) {
1107 LOG(LS_WARNING) << "Failed to pause playout";
1108 ret = false;
1109 }
1110 if (!channel->PauseSend()) {
1111 LOG(LS_WARNING) << "Failed to pause send";
1112 ret = false;
1113 }
1114 }
1115
1116 // Find the recording device id in VoiceEngine and set recording device.
1117 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1118 ret = false;
1119 }
1120 if (ret) {
1121 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1122 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1123 ret = false;
1124 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001125 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1126 if (ap)
1127 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 }
1129
1130 // Find the playout device id in VoiceEngine and set playout device.
1131 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1132 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1133 ret = false;
1134 }
1135 if (ret) {
1136 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001137 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001138 ret = false;
1139 }
1140 }
1141
1142 // Resume all audio playback and capture.
1143 for (ChannelList::const_iterator i = channels_.begin();
1144 i != channels_.end(); ++i) {
1145 WebRtcVoiceMediaChannel *channel = *i;
1146 if (!channel->ResumePlayout()) {
1147 LOG(LS_WARNING) << "Failed to resume playout";
1148 ret = false;
1149 }
1150 if (!channel->ResumeSend()) {
1151 LOG(LS_WARNING) << "Failed to resume send";
1152 ret = false;
1153 }
1154 }
1155
1156 // Resume local monitor.
1157 if (!ResumeLocalMonitor()) {
1158 LOG(LS_WARNING) << "Failed to resume local monitor";
1159 ret = false;
1160 }
1161
1162 if (ret) {
1163 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1164 << ") and speaker to (id="<< out_id << " name=" << out_name
1165 << ")";
1166 }
1167
1168 return ret;
1169#else
1170 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001171#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172}
1173
1174bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1175 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1176 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001177#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 *rtc_id = dev_id;
1179 return true;
1180#else
1181 // In Windows and Mac, we need to find the VoiceEngine device id by name
1182 // unless the input dev_id is the default device id.
1183 if (kDefaultAudioDeviceId == dev_id) {
1184 *rtc_id = dev_id;
1185 return true;
1186 }
1187
1188 // Get the number of VoiceEngine audio devices.
1189 int count = 0;
1190 if (is_input) {
1191 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1192 LOG_RTCERR0(GetNumOfRecordingDevices);
1193 return false;
1194 }
1195 } else {
1196 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1197 LOG_RTCERR0(GetNumOfPlayoutDevices);
1198 return false;
1199 }
1200 }
1201
1202 for (int i = 0; i < count; ++i) {
1203 char name[128];
1204 char guid[128];
1205 if (is_input) {
1206 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1207 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1208 } else {
1209 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1210 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1211 }
1212
1213 std::string webrtc_name(name);
1214 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1215 *rtc_id = i;
1216 return true;
1217 }
1218 }
1219 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1220 return false;
1221#endif
1222}
1223
1224bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1225 unsigned int ulevel;
1226 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1227 LOG_RTCERR1(GetSpeakerVolume, level);
1228 return false;
1229 }
1230 *level = ulevel;
1231 return true;
1232}
1233
1234bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001235 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1237 LOG_RTCERR1(SetSpeakerVolume, level);
1238 return false;
1239 }
1240 return true;
1241}
1242
1243int WebRtcVoiceEngine::GetInputLevel() {
1244 unsigned int ulevel;
1245 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1246 static_cast<int>(ulevel) : -1;
1247}
1248
1249bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1250 desired_local_monitor_enable_ = enable;
1251 return ChangeLocalMonitor(desired_local_monitor_enable_);
1252}
1253
1254bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1255 // The voe file api is not available in chrome.
1256 if (!voe_wrapper_->file()) {
1257 return false;
1258 }
1259 if (enable && !monitor_) {
1260 monitor_.reset(new WebRtcMonitorStream);
1261 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1262 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1263 // Must call Stop() because there are some cases where Start will report
1264 // failure but still change the state, and if we leave VE in the on state
1265 // then it could crash later when trying to invoke methods on our monitor.
1266 voe_wrapper_->file()->StopRecordingMicrophone();
1267 monitor_.reset();
1268 return false;
1269 }
1270 } else if (!enable && monitor_) {
1271 voe_wrapper_->file()->StopRecordingMicrophone();
1272 monitor_.reset();
1273 }
1274 return true;
1275}
1276
1277bool WebRtcVoiceEngine::PauseLocalMonitor() {
1278 return ChangeLocalMonitor(false);
1279}
1280
1281bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1282 return ChangeLocalMonitor(desired_local_monitor_enable_);
1283}
1284
1285const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1286 return codecs_;
1287}
1288
1289bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1290 return FindWebRtcCodec(in, NULL);
1291}
1292
1293// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1294bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1295 webrtc::CodecInst* out) {
1296 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1297 for (int i = 0; i < ncodecs; ++i) {
1298 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001299 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1301 voe_codec.rate, voe_codec.channels, 0);
1302 bool multi_rate = IsCodecMultiRate(voe_codec);
1303 // Allow arbitrary rates for ISAC to be specified.
1304 if (multi_rate) {
1305 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1306 codec.bitrate = 0;
1307 }
1308 if (codec.Matches(in)) {
1309 if (out) {
1310 // Fixup the payload type.
1311 voe_codec.pltype = in.id;
1312
1313 // Set bitrate if specified.
1314 if (multi_rate && in.bitrate != 0) {
1315 voe_codec.rate = in.bitrate;
1316 }
1317
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001318 // Reset G722 sample rate to 16000 to match WebRTC.
1319 MaybeFixupG722(&voe_codec, 16000);
1320
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001322 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001324 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1326 }
1327 *out = voe_codec;
1328 }
1329 return true;
1330 }
1331 }
1332 }
1333 return false;
1334}
1335const std::vector<RtpHeaderExtension>&
1336WebRtcVoiceEngine::rtp_header_extensions() const {
1337 return rtp_header_extensions_;
1338}
1339
1340void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1341 // if min_sev == -1, we keep the current log level.
1342 if (min_sev >= 0) {
1343 SetTraceFilter(SeverityToFilter(min_sev));
1344 }
1345 log_options_ = filter;
1346 SetTraceOptions(initialized_ ? log_options_ : "");
1347}
1348
1349int WebRtcVoiceEngine::GetLastEngineError() {
1350 return voe_wrapper_->error();
1351}
1352
1353void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1354 log_filter_ = filter;
1355 tracing_->SetTraceFilter(filter);
1356}
1357
1358// We suppport three different logging settings for VoiceEngine:
1359// 1. Observer callback that goes into talk diagnostic logfile.
1360// Use --logfile and --loglevel
1361//
1362// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1363// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1364//
1365// 3. EC log and dump for debugging QualityEngine.
1366// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1367//
1368// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1369// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1370void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1371 // Set encrypted trace file.
1372 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001373 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 std::vector<std::string>::iterator tracefile =
1375 std::find(opts.begin(), opts.end(), "tracefile");
1376 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1377 // Write encrypted debug output (at same loglevel) to file
1378 // EncryptedTraceFile no longer supported.
1379 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1380 LOG_RTCERR1(SetTraceFile, *tracefile);
1381 }
1382 }
1383
wu@webrtc.org97077a32013-10-25 21:18:33 +00001384 // Allow trace options to override the trace filter. We default
1385 // it to log_filter_ (as a translation of libjingle log levels)
1386 // elsewhere, but this allows clients to explicitly set webrtc
1387 // log levels.
1388 std::vector<std::string>::iterator tracefilter =
1389 std::find(opts.begin(), opts.end(), "tracefilter");
1390 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001392 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1393 }
1394 }
1395
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 // Set AEC dump file
1397 std::vector<std::string>::iterator recordEC =
1398 std::find(opts.begin(), opts.end(), "recordEC");
1399 if (recordEC != opts.end()) {
1400 ++recordEC;
1401 if (recordEC != opts.end())
1402 StartAecDump(recordEC->c_str());
1403 else
1404 StopAecDump();
1405 }
1406}
1407
1408// Ignore spammy trace messages, mostly from the stats API when we haven't
1409// gotten RTCP info yet from the remote side.
1410bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1411 static const char* kTracesToIgnore[] = {
1412 "\tfailed to GetReportBlockInformation",
1413 "GetRecCodec() failed to get received codec",
1414 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1415 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1416 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1417 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1418 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1419 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1420 "SenderInfoReceived No received SR",
1421 "StatisticsRTP() no statistics available",
1422 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1423 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1424 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1425 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1426 NULL
1427 };
1428 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1429 if (trace.find(*p) != std::string::npos) {
1430 return true;
1431 }
1432 }
1433 return false;
1434}
1435
1436void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1437 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001438 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001440 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001442 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001444 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447
1448 // Skip past boilerplate prefix text
1449 if (length < 72) {
1450 std::string msg(trace, length);
1451 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1452 LOG_V(sev) << msg;
1453 } else {
1454 std::string msg(trace + 71, length - 72);
1455 if (!ShouldIgnoreTrace(msg)) {
1456 LOG_V(sev) << "webrtc: " << msg;
1457 }
1458 }
1459}
1460
1461void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001462 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 WebRtcVoiceMediaChannel* channel = NULL;
1464 uint32 ssrc = 0;
1465 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1466 << channel_num << ".";
1467 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001468 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 channel->OnError(ssrc, err_code);
1470 } else {
1471 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1472 << " could not be found in channel list when error reported.";
1473 }
1474}
1475
1476bool WebRtcVoiceEngine::FindChannelAndSsrc(
1477 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001478 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479
1480 *channel = NULL;
1481 *ssrc = 0;
1482 // Find corresponding channel and ssrc
1483 for (ChannelList::const_iterator it = channels_.begin();
1484 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001485 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486 if ((*it)->FindSsrc(channel_num, ssrc)) {
1487 *channel = *it;
1488 return true;
1489 }
1490 }
1491
1492 return false;
1493}
1494
1495// This method will search through the WebRtcVoiceMediaChannels and
1496// obtain the voice engine's channel number.
1497bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1498 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001499 DCHECK(channel_num != NULL);
1500 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501
1502 *channel_num = -1;
1503 // Find corresponding channel for ssrc.
1504 for (ChannelList::const_iterator it = channels_.begin();
1505 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001506 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507 if (direction & MPD_RX) {
1508 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1509 }
1510 if (*channel_num == -1 && (direction & MPD_TX)) {
1511 *channel_num = (*it)->GetSendChannelNum(ssrc);
1512 }
1513 if (*channel_num != -1) {
1514 return true;
1515 }
1516 }
1517 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1518 return false;
1519}
1520
1521void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001522 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523 channels_.push_back(channel);
1524}
1525
1526void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001527 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 ChannelList::iterator i = std::find(channels_.begin(),
1529 channels_.end(),
1530 channel);
1531 if (i != channels_.end()) {
1532 channels_.erase(i);
1533 }
1534}
1535
1536void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1537 soundclips_.push_back(soundclip);
1538}
1539
1540void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1541 SoundclipList::iterator i = std::find(soundclips_.begin(),
1542 soundclips_.end(),
1543 soundclip);
1544 if (i != soundclips_.end()) {
1545 soundclips_.erase(i);
1546 }
1547}
1548
1549// Adjusts the default AGC target level by the specified delta.
1550// NB: If we start messing with other config fields, we'll want
1551// to save the current webrtc::AgcConfig as well.
1552bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1553 webrtc::AgcConfig config = default_agc_config_;
1554 config.targetLeveldBOv -= delta;
1555
1556 LOG(LS_INFO) << "Adjusting AGC level from default -"
1557 << default_agc_config_.targetLeveldBOv << "dB to -"
1558 << config.targetLeveldBOv << "dB";
1559
1560 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1561 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1562 return false;
1563 }
1564 return true;
1565}
1566
1567bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1568 webrtc::AudioDeviceModule* adm_sc) {
1569 if (initialized_) {
1570 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1571 return false;
1572 }
1573 if (adm_) {
1574 adm_->Release();
1575 adm_ = NULL;
1576 }
1577 if (adm) {
1578 adm_ = adm;
1579 adm_->AddRef();
1580 }
1581
1582 if (adm_sc_) {
1583 adm_sc_->Release();
1584 adm_sc_ = NULL;
1585 }
1586 if (adm_sc) {
1587 adm_sc_ = adm_sc;
1588 adm_sc_->AddRef();
1589 }
1590 return true;
1591}
1592
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001593bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1594 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001595 if (!aec_dump_file_stream) {
1596 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001597 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001598 LOG(LS_WARNING) << "Could not close file.";
1599 return false;
1600 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001601 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001602 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001603 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001604 LOG_RTCERR0(StartDebugRecording);
1605 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001606 return false;
1607 }
1608 is_dumping_aec_ = true;
1609 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001610}
1611
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612bool WebRtcVoiceEngine::RegisterProcessor(
1613 uint32 ssrc,
1614 VoiceProcessor* voice_processor,
1615 MediaProcessorDirection direction) {
1616 bool register_with_webrtc = false;
1617 int channel_id = -1;
1618 bool success = false;
1619 uint32* processor_ssrc = NULL;
1620 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1621 if (voice_processor == NULL || !found_channel) {
1622 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1623 << " foundChannel: " << found_channel;
1624 return false;
1625 }
1626
1627 webrtc::ProcessingTypes processing_type;
1628 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001629 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630 if (direction == MPD_RX) {
1631 processing_type = webrtc::kPlaybackAllChannelsMixed;
1632 if (SignalRxMediaFrame.is_empty()) {
1633 register_with_webrtc = true;
1634 processor_ssrc = &rx_processor_ssrc_;
1635 }
1636 SignalRxMediaFrame.connect(voice_processor,
1637 &VoiceProcessor::OnFrame);
1638 } else {
1639 processing_type = webrtc::kRecordingPerChannel;
1640 if (SignalTxMediaFrame.is_empty()) {
1641 register_with_webrtc = true;
1642 processor_ssrc = &tx_processor_ssrc_;
1643 }
1644 SignalTxMediaFrame.connect(voice_processor,
1645 &VoiceProcessor::OnFrame);
1646 }
1647 }
1648 if (register_with_webrtc) {
1649 // TODO(janahan): when registering consider instantiating a
1650 // a VoeMediaProcess object and not make the engine extend the interface.
1651 if (voe()->media() && voe()->media()->
1652 RegisterExternalMediaProcessing(channel_id,
1653 processing_type,
1654 *this) != -1) {
1655 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1656 << channel_id;
1657 *processor_ssrc = ssrc;
1658 success = true;
1659 } else {
1660 LOG_RTCERR2(RegisterExternalMediaProcessing,
1661 channel_id,
1662 processing_type);
1663 success = false;
1664 }
1665 } else {
1666 // If we don't have to register with the engine, we just needed to
1667 // connect a new processor, set success to true;
1668 success = true;
1669 }
1670 return success;
1671}
1672
1673bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1674 MediaProcessorDirection channel_direction,
1675 uint32 ssrc,
1676 VoiceProcessor* voice_processor,
1677 MediaProcessorDirection processor_direction) {
1678 bool success = true;
1679 FrameSignal* signal;
1680 webrtc::ProcessingTypes processing_type;
1681 uint32* processor_ssrc = NULL;
1682 if (channel_direction == MPD_RX) {
1683 signal = &SignalRxMediaFrame;
1684 processing_type = webrtc::kPlaybackAllChannelsMixed;
1685 processor_ssrc = &rx_processor_ssrc_;
1686 } else {
1687 signal = &SignalTxMediaFrame;
1688 processing_type = webrtc::kRecordingPerChannel;
1689 processor_ssrc = &tx_processor_ssrc_;
1690 }
1691
1692 int deregister_id = -1;
1693 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001694 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1696 signal->disconnect(voice_processor);
1697 int channel_id = -1;
1698 bool found_channel = FindChannelNumFromSsrc(ssrc,
1699 channel_direction,
1700 &channel_id);
1701 if (signal->is_empty() && found_channel) {
1702 deregister_id = channel_id;
1703 }
1704 }
1705 }
1706 if (deregister_id != -1) {
1707 if (voe()->media() &&
1708 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1709 processing_type) != -1) {
1710 *processor_ssrc = 0;
1711 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1712 << deregister_id;
1713 } else {
1714 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1715 deregister_id,
1716 processing_type);
1717 success = false;
1718 }
1719 }
1720 return success;
1721}
1722
1723bool WebRtcVoiceEngine::UnregisterProcessor(
1724 uint32 ssrc,
1725 VoiceProcessor* voice_processor,
1726 MediaProcessorDirection direction) {
1727 bool success = true;
1728 if (voice_processor == NULL) {
1729 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1730 << ssrc;
1731 return false;
1732 }
1733 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1734 success = false;
1735 }
1736 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1737 success = false;
1738 }
1739 return success;
1740}
1741
1742// Implementing method from WebRtc VoEMediaProcess interface
1743// Do not lock mux_channel_cs_ in this callback.
1744void WebRtcVoiceEngine::Process(int channel,
1745 webrtc::ProcessingTypes type,
1746 int16_t audio10ms[],
1747 int length,
1748 int sampling_freq,
1749 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001750 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001751 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1752 if (type == webrtc::kPlaybackAllChannelsMixed) {
1753 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1754 } else if (type == webrtc::kRecordingPerChannel) {
1755 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1756 } else {
1757 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1758 << " channel: " << channel << " type: " << type
1759 << " tx_ssrc: " << tx_processor_ssrc_
1760 << " rx_ssrc: " << rx_processor_ssrc_;
1761 }
1762}
1763
1764void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1765 if (!is_dumping_aec_) {
1766 // Start dumping AEC when we are not dumping.
1767 if (voe_wrapper_->processing()->StartDebugRecording(
1768 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001769 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001770 } else {
1771 is_dumping_aec_ = true;
1772 }
1773 }
1774}
1775
1776void WebRtcVoiceEngine::StopAecDump() {
1777 if (is_dumping_aec_) {
1778 // Stop dumping AEC when we are dumping.
1779 if (voe_wrapper_->processing()->StopDebugRecording() !=
1780 webrtc::AudioProcessing::kNoError) {
1781 LOG_RTCERR0(StopDebugRecording);
1782 }
1783 is_dumping_aec_ = false;
1784 }
1785}
1786
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001787int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001788 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001789}
1790
1791int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1792 return CreateVoiceChannel(voe_wrapper_.get());
1793}
1794
1795int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1796 return CreateVoiceChannel(voe_wrapper_sc_.get());
1797}
1798
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001799class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1800 : public AudioRenderer::Sink {
1801 public:
1802 WebRtcVoiceChannelRenderer(int ch,
1803 webrtc::AudioTransport* voe_audio_transport)
1804 : channel_(ch),
1805 voe_audio_transport_(voe_audio_transport),
1806 renderer_(NULL) {
1807 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001808 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001809
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001810 // Starts the rendering by setting a sink to the renderer to get data
1811 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001812 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001813 // TODO(xians): Make sure Start() is called only once.
1814 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001815 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001816 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001817 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001818 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001819 return;
1820 }
1821
1822 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1823 // in getUserMedia by default.
1824 renderer->AddChannel(channel_);
1825 renderer->SetSink(this);
1826 renderer_ = renderer;
1827 }
1828
1829 // Stops rendering by setting the sink of the renderer to NULL. No data
1830 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001831 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001832 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001833 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001834 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001835 return;
1836
1837 renderer_->RemoveChannel(channel_);
1838 renderer_->SetSink(NULL);
1839 renderer_ = NULL;
1840 }
1841
1842 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001843 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001844 void OnData(const void* audio_data,
1845 int bits_per_sample,
1846 int sample_rate,
1847 int number_of_channels,
1848 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001849 voe_audio_transport_->OnData(channel_,
1850 audio_data,
1851 bits_per_sample,
1852 sample_rate,
1853 number_of_channels,
1854 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001855 }
1856
1857 // Callback from the |renderer_| when it is going away. In case Start() has
1858 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001859 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001860 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001861 // Set |renderer_| to NULL to make sure no more callback will get into
1862 // the renderer.
1863 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001864 }
1865
1866 // Accessor to the VoE channel ID.
1867 int channel() const { return channel_; }
1868
1869 private:
1870 const int channel_;
1871 webrtc::AudioTransport* const voe_audio_transport_;
1872
1873 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1874 // PeerConnection will make sure invalidating the pointer before the object
1875 // goes away.
1876 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001877
1878 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001879 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001880};
1881
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001883WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1884 : engine_(engine),
1885 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001886 send_bitrate_setting_(false),
1887 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 options_(),
1889 dtmf_allowed_(false),
1890 desired_playout_(false),
1891 nack_enabled_(false),
1892 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001893 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 desired_send_(SEND_NOTHING),
1895 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001896 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 default_receive_ssrc_(0) {
1898 engine->RegisterChannel(this);
1899 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1900 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001901 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902}
1903
1904WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1905 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1906 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001907 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001909 // Remove any remaining send streams, the default channel will be deleted
1910 // later.
1911 while (!send_channels_.empty())
1912 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913
1914 // Unregister ourselves from the engine.
1915 engine()->UnregisterChannel(this);
1916 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001917 while (!receive_channels_.empty()) {
1918 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001920 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001922 // Delete the default channel.
1923 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924}
1925
1926bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1927 LOG(LS_INFO) << "Setting voice channel options: "
1928 << options.ToString();
1929
wu@webrtc.orgde305012013-10-31 15:40:38 +00001930 // Check if DSCP value is changed from previous.
1931 bool dscp_option_changed = (options_.dscp != options.dscp);
1932
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001933 // TODO(xians): Add support to set different options for different send
1934 // streams after we support multiple APMs.
1935
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 // We retain all of the existing options, and apply the given ones
1937 // on top. This means there is no way to "clear" options such that
1938 // they go back to the engine default.
1939 options_.SetAll(options);
1940
1941 if (send_ != SEND_NOTHING) {
1942 if (!engine()->SetOptionOverrides(options_)) {
1943 LOG(LS_WARNING) <<
1944 "Failed to engine SetOptionOverrides during channel SetOptions.";
1945 return false;
1946 }
1947 } else {
1948 // Will be interpreted when appropriate.
1949 }
1950
wu@webrtc.org97077a32013-10-25 21:18:33 +00001951 // Receiver-side auto gain control happens per channel, so set it here from
1952 // options. Note that, like conference mode, setting it on the engine won't
1953 // have the desired effect, since voice channels don't inherit options from
1954 // the media engine when those options are applied per-channel.
1955 bool rx_auto_gain_control;
1956 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1957 if (engine()->voe()->processing()->SetRxAgcStatus(
1958 voe_channel(), rx_auto_gain_control,
1959 webrtc::kAgcFixedDigital) == -1) {
1960 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1961 return false;
1962 } else {
1963 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1964 << " with mode " << webrtc::kAgcFixedDigital;
1965 }
1966 }
1967 if (options.rx_agc_target_dbov.IsSet() ||
1968 options.rx_agc_digital_compression_gain.IsSet() ||
1969 options.rx_agc_limiter.IsSet()) {
1970 webrtc::AgcConfig config;
1971 // If only some of the options are being overridden, get the current
1972 // settings for the channel and bail if they aren't available.
1973 if (!options.rx_agc_target_dbov.IsSet() ||
1974 !options.rx_agc_digital_compression_gain.IsSet() ||
1975 !options.rx_agc_limiter.IsSet()) {
1976 if (engine()->voe()->processing()->GetRxAgcConfig(
1977 voe_channel(), config) != 0) {
1978 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1979 << "channel " << voe_channel() << ". Since not all rx "
1980 << "agc options are specified, unable to safely set rx "
1981 << "agc options.";
1982 return false;
1983 }
1984 }
1985 config.targetLeveldBOv =
1986 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1987 config.targetLeveldBOv);
1988 config.digitalCompressionGaindB =
1989 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1990 config.digitalCompressionGaindB);
1991 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1992 config.limiterEnable);
1993 if (engine()->voe()->processing()->SetRxAgcConfig(
1994 voe_channel(), config) == -1) {
1995 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1996 config.digitalCompressionGaindB, config.limiterEnable);
1997 return false;
1998 }
1999 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002000 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002001 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002002 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002003 dscp = kAudioDscpValue;
2004 if (MediaChannel::SetDscp(dscp) != 0) {
2005 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
2006 }
2007 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00002008
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002009 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002011 LOG(LS_INFO) << "Set voice channel options. Current options: "
2012 << options_.ToString();
2013 return true;
2014}
2015
2016bool WebRtcVoiceMediaChannel::SetRecvCodecs(
2017 const std::vector<AudioCodec>& codecs) {
2018 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019 LOG(LS_INFO) << "Setting receive voice codecs:";
2020
2021 std::vector<AudioCodec> new_codecs;
2022 // Find all new codecs. We allow adding new codecs but don't allow changing
2023 // the payload type of codecs that is already configured since we might
2024 // already be receiving packets with that payload type.
2025 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002026 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 AudioCodec old_codec;
2028 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2029 if (old_codec.id != it->id) {
2030 LOG(LS_ERROR) << it->name << " payload type changed.";
2031 return false;
2032 }
2033 } else {
2034 new_codecs.push_back(*it);
2035 }
2036 }
2037 if (new_codecs.empty()) {
2038 // There are no new codecs to configure. Already configured codecs are
2039 // never removed.
2040 return true;
2041 }
2042
2043 if (playout_) {
2044 // Receive codecs can not be changed while playing. So we temporarily
2045 // pause playout.
2046 PausePlayout();
2047 }
2048
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002049 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2051 it != new_codecs.end() && ret; ++it) {
2052 webrtc::CodecInst voe_codec;
2053 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2054 LOG(LS_INFO) << ToString(*it);
2055 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002056 if (default_receive_ssrc_ == 0) {
2057 // Set the receive codecs on the default channel explicitly if the
2058 // default channel is not used by |receive_channels_|, this happens in
2059 // conference mode or in non-conference mode when there is no playout
2060 // channel.
2061 // TODO(xians): Figure out how we use the default channel in conference
2062 // mode.
2063 if (engine()->voe()->codec()->SetRecPayloadType(
2064 voe_channel(), voe_codec) == -1) {
2065 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2066 ret = false;
2067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002068 }
2069
2070 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002071 for (ChannelMap::iterator it = receive_channels_.begin();
2072 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002074 it->second->channel(), voe_codec) == -1) {
2075 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002076 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 ret = false;
2078 }
2079 }
2080 } else {
2081 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2082 ret = false;
2083 }
2084 }
2085 if (ret) {
2086 recv_codecs_ = codecs;
2087 }
2088
2089 if (desired_playout_ && !playout_) {
2090 ResumePlayout();
2091 }
2092 return ret;
2093}
2094
2095bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002096 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002097 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002098 engine()->voe()->codec()->SetVADStatus(channel, false);
2099 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002100 engine()->voe()->rtp()->SetREDStatus(channel, false);
2101 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102
2103 // Scan through the list to figure out the codec to use for sending, along
2104 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002105 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106 webrtc::CodecInst send_codec;
2107 memset(&send_codec, 0, sizeof(send_codec));
2108
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002109 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002110 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01002111 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00002112 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002113
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002114 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2116 it != codecs.end(); ++it) {
2117 // Ignore codecs we don't know about. The negotiation step should prevent
2118 // this, but double-check to be sure.
2119 webrtc::CodecInst voe_codec;
2120 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002121 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 continue;
2123 }
2124
Minyue Li7100dcd2015-03-27 05:05:59 +01002125 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002126 // Skip telephone-event/CN codec, which will be handled later.
2127 continue;
2128 }
2129
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 // We'll use the first codec in the list to actually send audio data.
2131 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002132 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002133 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01002134 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002135 // Parse out the RED parameters. If we fail, just ignore RED;
2136 // we don't support all possible params/usage scenarios.
2137 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2138 continue;
2139 }
2140
2141 // Enable redundant encoding of the specified codec. Treat any
2142 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002143 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2144 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2145 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002146 return false;
2147 }
2148 } else {
2149 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002150 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01002151 // For Opus as the send codec, we are to determine inband FEC, maximum
2152 // playback rate, and opus internal dtx.
2153 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002154 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01002155 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002156 }
Brave Yao5225dd82015-03-26 07:39:19 +08002157
2158 // Set packet size if the AudioCodec param kCodecParamPTime is set.
2159 int ptime_ms = 0;
2160 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
2161 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2162 LOG(LS_WARNING) << "Failed to set packet size for codec "
2163 << send_codec.plname;
2164 return false;
2165 }
2166 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002167 }
2168 found_send_codec = true;
2169 break;
2170 }
2171
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002172 if (nack_enabled_ != nack_enabled) {
2173 SetNack(channel, nack_enabled);
2174 nack_enabled_ = nack_enabled;
2175 }
2176
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002177 if (!found_send_codec) {
2178 LOG(LS_WARNING) << "Received empty list of codecs.";
2179 return false;
2180 }
2181
2182 // Set the codec immediately, since SetVADStatus() depends on whether
2183 // the current codec is mono or stereo.
2184 if (!SetSendCodec(channel, send_codec))
2185 return false;
2186
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002187 // FEC should be enabled after SetSendCodec.
2188 if (enable_codec_fec) {
2189 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2190 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002191 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2192 // Enable codec internal FEC. Treat any failure as fatal internal error.
2193 LOG_RTCERR2(SetFECStatus, channel, true);
2194 return false;
2195 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002196 }
2197
Minyue Li7100dcd2015-03-27 05:05:59 +01002198 if (IsCodec(send_codec, kOpusCodecName)) {
2199 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2200 // send codec has to be Opus.
2201
2202 // Set Opus internal DTX.
2203 LOG(LS_INFO) << "Attempt to "
2204 << GetEnableString(enable_opus_dtx)
2205 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002206 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002207 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2208 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2209 return false;
2210 }
2211
2212 // If opus_max_playback_rate <= 0, the default maximum playback rate
2213 // (48 kHz) will be used.
2214 if (opus_max_playback_rate > 0) {
2215 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2216 << opus_max_playback_rate
2217 << " Hz on channel "
2218 << channel;
2219 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2220 channel, opus_max_playback_rate) == -1) {
2221 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2222 return false;
2223 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002224 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002225 }
2226
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002227 // Always update the |send_codec_| to the currently set send codec.
2228 send_codec_.reset(new webrtc::CodecInst(send_codec));
2229
minyue@webrtc.org26236952014-10-29 02:27:08 +00002230 if (send_bitrate_setting_) {
2231 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002232 }
2233
2234 // Loop through the codecs list again to config the telephone-event/CN codec.
2235 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2236 it != codecs.end(); ++it) {
2237 // Ignore codecs we don't know about. The negotiation step should prevent
2238 // this, but double-check to be sure.
2239 webrtc::CodecInst voe_codec;
2240 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2241 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2242 continue;
2243 }
2244
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002245 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2246 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002247 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002248 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2249 channel, it->id) == -1) {
2250 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2251 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002253 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002254 // Turn voice activity detection/comfort noise on if supported.
2255 // Set the wideband CN payload type appropriately.
2256 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 webrtc::PayloadFrequencies cn_freq;
2258 switch (it->clockrate) {
2259 case 8000:
2260 cn_freq = webrtc::kFreq8000Hz;
2261 break;
2262 case 16000:
2263 cn_freq = webrtc::kFreq16000Hz;
2264 break;
2265 case 32000:
2266 cn_freq = webrtc::kFreq32000Hz;
2267 break;
2268 default:
2269 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2270 << " not supported.";
2271 continue;
2272 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002273 // Set the CN payloadtype and the VAD status.
2274 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2275 if (cn_freq != webrtc::kFreq8000Hz) {
2276 if (engine()->voe()->codec()->SetSendCNPayloadType(
2277 channel, it->id, cn_freq) == -1) {
2278 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2279 // TODO(ajm): This failure condition will be removed from VoE.
2280 // Restore the return here when we update to a new enough webrtc.
2281 //
2282 // Not returning false because the SetSendCNPayloadType will fail if
2283 // the channel is already sending.
2284 // This can happen if the remote description is applied twice, for
2285 // example in the case of ROAP on top of JSEP, where both side will
2286 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002287 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002288 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002289 // Only turn on VAD if we have a CN payload type that matches the
2290 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002291 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2292 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2293 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002294 LOG(LS_INFO) << "Enabling VAD";
2295 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2296 LOG_RTCERR2(SetVADStatus, channel, true);
2297 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298 }
2299 }
2300 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002301 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002302 return true;
2303}
2304
2305bool WebRtcVoiceMediaChannel::SetSendCodecs(
2306 const std::vector<AudioCodec>& codecs) {
2307 dtmf_allowed_ = false;
2308 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2309 it != codecs.end(); ++it) {
2310 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002311 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002312 dtmf_allowed_ = true;
2313 }
2314 }
2315
2316 // Cache the codecs in order to configure the channel created later.
2317 send_codecs_ = codecs;
2318 for (ChannelMap::iterator iter = send_channels_.begin();
2319 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002320 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002321 return false;
2322 }
2323 }
2324
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002325 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002326 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 return true;
2328}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002329
2330void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2331 bool nack_enabled) {
2332 for (ChannelMap::const_iterator it = channels.begin();
2333 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002334 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002335 }
2336}
2337
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002338void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002340 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2342 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002343 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2345 }
2346}
2347
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002348bool WebRtcVoiceMediaChannel::SetSendCodec(
2349 const webrtc::CodecInst& send_codec) {
2350 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2351 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002352 for (ChannelMap::iterator iter = send_channels_.begin();
2353 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002354 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002355 return false;
2356 }
2357
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002358 return true;
2359}
2360
2361bool WebRtcVoiceMediaChannel::SetSendCodec(
2362 int channel, const webrtc::CodecInst& send_codec) {
2363 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2364 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2365
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002366 webrtc::CodecInst current_codec;
2367 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2368 (send_codec == current_codec)) {
2369 // Codec is already configured, we can return without setting it again.
2370 return true;
2371 }
2372
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002373 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2374 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 return false;
2376 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 return true;
2378}
2379
2380bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2381 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002382 if (receive_extensions_ == extensions) {
2383 return true;
2384 }
2385
2386 // The default channel may or may not be in |receive_channels_|. Set the rtp
2387 // header extensions for default channel regardless.
2388 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2389 return false;
2390 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002391
2392 // Loop through all receive channels and enable/disable the extensions.
2393 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2394 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002395 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2396 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002397 return false;
2398 }
2399 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002400
2401 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002402
2403 // Recreate AudioReceiveStream:s.
2404 {
2405 std::vector<webrtc::RtpExtension> exts;
2406
2407 const RtpHeaderExtension* audio_level_extension =
2408 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2409 if (audio_level_extension) {
2410 exts.push_back({
2411 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2412 }
2413
2414 const RtpHeaderExtension* send_time_extension =
2415 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2416 if (send_time_extension) {
2417 exts.push_back({
2418 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2419 }
2420
2421 recv_rtp_extensions_.swap(exts);
2422 SetCall(call_);
2423 }
2424
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002425 return true;
2426}
2427
2428bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2429 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002430 const RtpHeaderExtension* audio_level_extension =
2431 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2432 if (!SetHeaderExtension(
2433 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2434 audio_level_extension)) {
2435 return false;
2436 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002437
2438 const RtpHeaderExtension* send_time_extension =
2439 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2440 if (!SetHeaderExtension(
2441 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2442 send_time_extension)) {
2443 return false;
2444 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002445
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 return true;
2447}
2448
2449bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2450 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002451 if (send_extensions_ == extensions) {
2452 return true;
2453 }
2454
2455 // The default channel may or may not be in |send_channels_|. Set the rtp
2456 // header extensions for default channel regardless.
2457
2458 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2459 return false;
2460 }
2461
2462 // Loop through all send channels and enable/disable the extensions.
2463 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2464 channel_it != send_channels_.end(); ++channel_it) {
2465 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2466 extensions)) {
2467 return false;
2468 }
2469 }
2470
2471 send_extensions_ = extensions;
2472 return true;
2473}
2474
2475bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2476 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002477 const RtpHeaderExtension* audio_level_extension =
2478 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002479
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002480 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002481 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002482 audio_level_extension)) {
2483 return false;
2484 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002485
2486 const RtpHeaderExtension* send_time_extension =
2487 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002488 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002489 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002490 send_time_extension)) {
2491 return false;
2492 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 return true;
2495}
2496
2497bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2498 desired_playout_ = playout;
2499 return ChangePlayout(desired_playout_);
2500}
2501
2502bool WebRtcVoiceMediaChannel::PausePlayout() {
2503 return ChangePlayout(false);
2504}
2505
2506bool WebRtcVoiceMediaChannel::ResumePlayout() {
2507 return ChangePlayout(desired_playout_);
2508}
2509
2510bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2511 if (playout_ == playout) {
2512 return true;
2513 }
2514
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002515 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002517 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 // Only toggle the default channel if we don't have any other channels.
2519 result = SetPlayout(voe_channel(), playout);
2520 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002521 for (ChannelMap::iterator it = receive_channels_.begin();
2522 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002523 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002524 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002525 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526 result = false;
2527 }
2528 }
2529
2530 if (result) {
2531 playout_ = playout;
2532 }
2533 return result;
2534}
2535
2536bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2537 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002538 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002539 return ChangeSend(desired_send_);
2540 return true;
2541}
2542
2543bool WebRtcVoiceMediaChannel::PauseSend() {
2544 return ChangeSend(SEND_NOTHING);
2545}
2546
2547bool WebRtcVoiceMediaChannel::ResumeSend() {
2548 return ChangeSend(desired_send_);
2549}
2550
2551bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2552 if (send_ == send) {
2553 return true;
2554 }
2555
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002556 // Change the settings on each send channel.
2557 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558 engine()->SetOptionOverrides(options_);
2559
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002560 // Change the settings on each send channel.
2561 for (ChannelMap::iterator iter = send_channels_.begin();
2562 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002563 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002564 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002565 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002566
2567 // Clear up the options after stopping sending.
2568 if (send == SEND_NOTHING)
2569 engine()->ClearOptionOverrides();
2570
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571 send_ = send;
2572 return true;
2573}
2574
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002575bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2576 if (send == SEND_MICROPHONE) {
2577 if (engine()->voe()->base()->StartSend(channel) == -1) {
2578 LOG_RTCERR1(StartSend, channel);
2579 return false;
2580 }
2581 if (engine()->voe()->file() &&
2582 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2583 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2584 return false;
2585 }
2586 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002587 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002588 if (engine()->voe()->base()->StopSend(channel) == -1) {
2589 LOG_RTCERR1(StopSend, channel);
2590 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002591 }
2592 }
2593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 return true;
2595}
2596
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002597// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002598void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2599 if (engine()->voe()->network()->RegisterExternalTransport(
2600 channel, *this) == -1) {
2601 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2602 }
2603
2604 // Enable RTCP (for quality stats and feedback messages)
2605 EnableRtcp(channel);
2606
2607 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2608 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002609
2610 // Set RTP header extension for the new channel.
2611 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002612}
2613
2614bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2615 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2616 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2617 }
2618
2619 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2620 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002621 return false;
2622 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002623
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002624 return true;
2625}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002626
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002627bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2628 // If the default channel is already used for sending create a new channel
2629 // otherwise use the default channel for sending.
2630 int channel = GetSendChannelNum(sp.first_ssrc());
2631 if (channel != -1) {
2632 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2633 return false;
2634 }
2635
2636 bool default_channel_is_available = true;
2637 for (ChannelMap::const_iterator iter = send_channels_.begin();
2638 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002639 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002640 default_channel_is_available = false;
2641 break;
2642 }
2643 }
2644 if (default_channel_is_available) {
2645 channel = voe_channel();
2646 } else {
2647 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002648 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002649 if (channel == -1) {
2650 LOG_RTCERR0(CreateChannel);
2651 return false;
2652 }
2653
2654 ConfigureSendChannel(channel);
2655 }
2656
2657 // Save the channel to send_channels_, so that RemoveSendStream() can still
2658 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002659 webrtc::AudioTransport* audio_transport =
2660 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002661 send_channels_.insert(std::make_pair(
2662 sp.first_ssrc(),
2663 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002664
2665 // Set the send (local) SSRC.
2666 // If there are multiple send SSRCs, we can only set the first one here, and
2667 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2668 // (with a codec requires multiple SSRC(s)).
2669 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2670 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2671 return false;
2672 }
2673
2674 // At this point the channel's local SSRC has been updated. If the channel is
2675 // the default channel make sure that all the receive channels are updated as
2676 // well. Receive channels have to have the same SSRC as the default channel in
2677 // order to send receiver reports with this SSRC.
2678 if (IsDefaultChannel(channel)) {
2679 for (ChannelMap::const_iterator it = receive_channels_.begin();
2680 it != receive_channels_.end(); ++it) {
2681 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002682 if (!IsDefaultChannel(it->second->channel())) {
2683 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002684 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002685 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002686 return false;
2687 }
2688 }
2689 }
2690 }
2691
2692 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002693 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2694 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002695 }
2696
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002697 // Set the current codecs to be used for the new channel.
2698 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002699 return false;
2700
2701 return ChangeSend(channel, desired_send_);
2702}
2703
2704bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2705 ChannelMap::iterator it = send_channels_.find(ssrc);
2706 if (it == send_channels_.end()) {
2707 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2708 << " which doesn't exist.";
2709 return false;
2710 }
2711
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002712 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002713 ChangeSend(channel, SEND_NOTHING);
2714
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002715 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2716 // this will disconnect the audio renderer with the send channel.
2717 delete it->second;
2718 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002719
2720 if (IsDefaultChannel(channel)) {
2721 // Do not delete the default channel since the receive channels depend on
2722 // the default channel, recycle it instead.
2723 ChangeSend(channel, SEND_NOTHING);
2724 } else {
2725 // Clean up and delete the send channel.
2726 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2727 << " with VoiceEngine channel #" << channel << ".";
2728 if (!DeleteChannel(channel))
2729 return false;
2730 }
2731
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002732 if (send_channels_.empty())
2733 ChangeSend(SEND_NOTHING);
2734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 return true;
2736}
2737
2738bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002739 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002740 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741
2742 if (!VERIFY(sp.ssrcs.size() == 1))
2743 return false;
2744 uint32 ssrc = sp.first_ssrc();
2745
wu@webrtc.org78187522013-10-07 23:32:02 +00002746 if (ssrc == 0) {
2747 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2748 return false;
2749 }
2750
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2752 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 return false;
2754 }
2755
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002756 TryAddAudioRecvStream(ssrc);
2757
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002758 // Reuse default channel for recv stream in non-conference mode call
2759 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002760 webrtc::AudioTransport* audio_transport =
2761 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002763 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2764 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002766 default_receive_ssrc_,
2767 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002768 return SetPlayout(voe_channel(), playout_);
2769 }
2770
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002772 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 if (channel == -1) {
2774 LOG_RTCERR0(CreateChannel);
2775 return false;
2776 }
2777
wu@webrtc.org78187522013-10-07 23:32:02 +00002778 if (!ConfigureRecvChannel(channel)) {
2779 DeleteChannel(channel);
2780 return false;
2781 }
2782
2783 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002784 std::make_pair(
2785 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002786
2787 LOG(LS_INFO) << "New audio stream " << ssrc
2788 << " registered to VoiceEngine channel #"
2789 << channel << ".";
2790 return true;
2791}
2792
2793bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002794 // Configure to use external transport, like our default channel.
2795 if (engine()->voe()->network()->RegisterExternalTransport(
2796 channel, *this) == -1) {
2797 LOG_RTCERR2(SetExternalTransport, channel, this);
2798 return false;
2799 }
2800
2801 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002802 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2804 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002805 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806 return false;
2807 }
2808 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002809 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002810 return false;
2811 }
2812
2813 // Use the same recv payload types as our default channel.
2814 ResetRecvCodecs(channel);
2815 if (!recv_codecs_.empty()) {
2816 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2817 it != recv_codecs_.end(); ++it) {
2818 webrtc::CodecInst voe_codec;
2819 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2820 voe_codec.pltype = it->id;
2821 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2822 if (engine()->voe()->codec()->GetRecPayloadType(
2823 voe_channel(), voe_codec) != -1) {
2824 if (engine()->voe()->codec()->SetRecPayloadType(
2825 channel, voe_codec) == -1) {
2826 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2827 return false;
2828 }
2829 }
2830 }
2831 }
2832 }
2833
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002834 if (InConferenceMode()) {
2835 // To be in par with the video, voe_channel() is not used for receiving in
2836 // a conference call.
2837 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2838 // This is the first stream in a multi user meeting. We can now
2839 // disable playback of the default stream. This since the default
2840 // stream will probably have received some initial packets before
2841 // the new stream was added. This will mean that the CN state from
2842 // the default channel will be mixed in with the other streams
2843 // throughout the whole meeting, which might be disturbing.
2844 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2845 SetPlayout(voe_channel(), false);
2846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002848 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002850 // Set RTP header extension for the new channel.
2851 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2852 return false;
2853 }
2854
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855 return SetPlayout(channel, playout_);
2856}
2857
2858bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002859 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002860 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002861 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002862 if (it == receive_channels_.end()) {
2863 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2864 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002865 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002866 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002867
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002868 TryRemoveAudioRecvStream(ssrc);
2869
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002870 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2871 // will disconnect the audio renderer with the receive channel.
2872 // Cache the channel before the deletion.
2873 const int channel = it->second->channel();
2874 delete it->second;
2875 receive_channels_.erase(it);
2876
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002877 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002878 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002879 // Recycle the default channel is for recv stream.
2880 if (playout_)
2881 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002882
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002883 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002884 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002885 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002886
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002887 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002888 << " with VoiceEngine channel #" << channel << ".";
2889 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002890 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002891
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002892 bool enable_default_channel_playout = false;
2893 if (receive_channels_.empty()) {
2894 // The last stream was removed. We can now enable the default
2895 // channel for new channels to be played out immediately without
2896 // waiting for AddStream messages.
2897 // We do this for both conference mode and non-conference mode.
2898 // TODO(oja): Does the default channel still have it's CN state?
2899 enable_default_channel_playout = true;
2900 }
2901 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2902 default_receive_ssrc_ != 0) {
2903 // Only the default channel is active, enable the playout on default
2904 // channel.
2905 enable_default_channel_playout = true;
2906 }
2907 if (enable_default_channel_playout && playout_) {
2908 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2909 SetPlayout(voe_channel(), true);
2910 }
2911
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 return true;
2913}
2914
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002915bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2916 AudioRenderer* renderer) {
2917 ChannelMap::iterator it = receive_channels_.find(ssrc);
2918 if (it == receive_channels_.end()) {
2919 if (renderer) {
2920 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002921 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002922 return false;
2923 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002924
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002925 // The channel likely has gone away, do nothing.
2926 return true;
2927 }
2928
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002929 if (renderer)
2930 it->second->Start(renderer);
2931 else
2932 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002933
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002934 return true;
2935}
2936
2937bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2938 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002939 ChannelMap::iterator it = send_channels_.find(ssrc);
2940 if (it == send_channels_.end()) {
2941 if (renderer) {
2942 // Return an error if trying to set a valid renderer with an invalid ssrc.
2943 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2944 return false;
2945 }
2946
2947 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002948 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002949 }
2950
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002951 if (renderer)
2952 it->second->Start(renderer);
2953 else
2954 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002955
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 return true;
2957}
2958
2959bool WebRtcVoiceMediaChannel::GetActiveStreams(
2960 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002961 // In conference mode, the default channel should not be in
2962 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002963 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002964 for (ChannelMap::iterator it = receive_channels_.begin();
2965 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002966 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967 if (level > 0) {
2968 actives->push_back(std::make_pair(it->first, level));
2969 }
2970 }
2971 return true;
2972}
2973
2974int WebRtcVoiceMediaChannel::GetOutputLevel() {
2975 // return the highest output level of all streams
2976 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002977 for (ChannelMap::iterator it = receive_channels_.begin();
2978 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002979 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002980 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981 }
2982 return highest;
2983}
2984
2985int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2986 int ret;
2987 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2988 // In case of error, log the info and continue
2989 LOG_RTCERR0(TimeSinceLastTyping);
2990 ret = -1;
2991 } else {
2992 ret *= 1000; // We return ms, webrtc returns seconds.
2993 }
2994 return ret;
2995}
2996
2997void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2998 int cost_per_typing, int reporting_threshold, int penalty_decay,
2999 int type_event_delay) {
3000 if (engine()->voe()->processing()->SetTypingDetectionParameters(
3001 time_window, cost_per_typing,
3002 reporting_threshold, penalty_decay, type_event_delay) == -1) {
3003 // In case of error, log the info and continue
3004 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
3005 cost_per_typing, reporting_threshold, penalty_decay,
3006 type_event_delay);
3007 }
3008}
3009
3010bool WebRtcVoiceMediaChannel::SetOutputScaling(
3011 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003012 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003013 // Collect the channels to scale the output volume.
3014 std::vector<int> channels;
3015 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003016 // Default channel is not in receive_channels_ if it is not being used for
3017 // playout.
3018 if (default_receive_ssrc_ == 0)
3019 channels.push_back(voe_channel());
3020 for (ChannelMap::const_iterator it = receive_channels_.begin();
3021 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003022 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 }
3024 } else { // Collect only the channel of the specified ssrc.
3025 int channel = GetReceiveChannelNum(ssrc);
3026 if (-1 == channel) {
3027 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3028 return false;
3029 }
3030 channels.push_back(channel);
3031 }
3032
3033 // Scale the output volume for the collected channels. We first normalize to
3034 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00003035 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003036 if (scale > 0.0001f) {
3037 left /= scale;
3038 right /= scale;
3039 }
3040 for (std::vector<int>::const_iterator it = channels.begin();
3041 it != channels.end(); ++it) {
3042 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
3043 *it, scale)) {
3044 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
3045 return false;
3046 }
3047 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
3048 *it, static_cast<float>(left), static_cast<float>(right))) {
3049 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
3050 // Do not return if fails. SetOutputVolumePan is not available for all
3051 // pltforms.
3052 }
3053 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
3054 << " right=" << right * scale
3055 << " for channel " << *it << " and ssrc " << ssrc;
3056 }
3057 return true;
3058}
3059
3060bool WebRtcVoiceMediaChannel::GetOutputScaling(
3061 uint32 ssrc, double* left, double* right) {
3062 if (!left || !right) return false;
3063
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003064 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003065 // Determine which channel based on ssrc.
3066 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3067 if (channel == -1) {
3068 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3069 return false;
3070 }
3071
3072 float scaling;
3073 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3074 channel, scaling)) {
3075 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3076 return false;
3077 }
3078
3079 float left_pan;
3080 float right_pan;
3081 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3082 channel, left_pan, right_pan)) {
3083 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3084 // If GetOutputVolumePan fails, we use the default left and right pan.
3085 left_pan = 1.0f;
3086 right_pan = 1.0f;
3087 }
3088
3089 *left = scaling * left_pan;
3090 *right = scaling * right_pan;
3091 return true;
3092}
3093
3094bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3095 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3096 return true;
3097}
3098
3099bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3100 bool play, bool loop) {
3101 if (!ringback_tone_) {
3102 return false;
3103 }
3104
3105 // The voe file api is not available in chrome.
3106 if (!engine()->voe()->file()) {
3107 return false;
3108 }
3109
3110 // Determine which VoiceEngine channel to play on.
3111 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3112 if (channel == -1) {
3113 return false;
3114 }
3115
3116 // Make sure the ringtone is cued properly, and play it out.
3117 if (play) {
3118 ringback_tone_->set_loop(loop);
3119 ringback_tone_->Rewind();
3120 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3121 ringback_tone_.get()) == -1) {
3122 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3123 LOG(LS_ERROR) << "Unable to start ringback tone";
3124 return false;
3125 }
3126 ringback_channels_.insert(channel);
3127 LOG(LS_INFO) << "Started ringback on channel " << channel;
3128 } else {
3129 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3130 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3131 LOG_RTCERR1(StopPlayingFileLocally, channel);
3132 return false;
3133 }
3134 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3135 ringback_channels_.erase(channel);
3136 }
3137
3138 return true;
3139}
3140
3141bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3142 return dtmf_allowed_;
3143}
3144
3145bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3146 int duration, int flags) {
3147 if (!dtmf_allowed_) {
3148 return false;
3149 }
3150
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151 // Send the event.
3152 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003153 int channel = -1;
3154 if (ssrc == 0) {
3155 bool default_channel_is_inuse = false;
3156 for (ChannelMap::const_iterator iter = send_channels_.begin();
3157 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003158 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003159 default_channel_is_inuse = true;
3160 break;
3161 }
3162 }
3163 if (default_channel_is_inuse) {
3164 channel = voe_channel();
3165 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003166 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003167 }
3168 } else {
3169 channel = GetSendChannelNum(ssrc);
3170 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003171 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3173 << ssrc << " is not in use.";
3174 return false;
3175 }
3176 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003177 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3178 channel, event, true, duration) == -1) {
3179 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180 return false;
3181 }
3182 }
3183
3184 // Play the event.
3185 if (flags & cricket::DF_PLAY) {
3186 // Play DTMF tone locally.
3187 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3188 LOG_RTCERR2(PlayDtmfTone, event, duration);
3189 return false;
3190 }
3191 }
3192
3193 return true;
3194}
3195
wu@webrtc.orga9890802013-12-13 00:21:03 +00003196void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003197 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003198 DCHECK(thread_checker_.CalledOnValidThread());
3199
3200 // If hooked up to a "Call", forward packet there too.
3201 if (call_) {
3202 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3203 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3204 }
3205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206 // Pick which channel to send this packet to. If this packet doesn't match
3207 // any multiplexed streams, just send it to the default channel. Otherwise,
3208 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003209 int which_channel =
3210 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 if (which_channel == -1) {
3212 which_channel = voe_channel();
3213 }
3214
3215 // Stop any ringback that might be playing on the channel.
3216 // It's possible the ringback has already stopped, ih which case we'll just
3217 // use the opportunity to remove the channel from ringback_channels_.
3218 if (engine()->voe()->file()) {
3219 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3220 if (it != ringback_channels_.end()) {
3221 if (engine()->voe()->file()->IsPlayingFileLocally(
3222 which_channel) == 1) {
3223 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3224 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3225 << " due to incoming media";
3226 }
3227 ringback_channels_.erase(which_channel);
3228 }
3229 }
3230
3231 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003232 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003233 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003234 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235}
3236
wu@webrtc.orga9890802013-12-13 00:21:03 +00003237void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003238 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003239 DCHECK(thread_checker_.CalledOnValidThread());
3240
3241 // If hooked up to a "Call", forward packet there too.
3242 if (call_) {
3243 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3244 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3245 }
3246
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003247 // Sending channels need all RTCP packets with feedback information.
3248 // Even sender reports can contain attached report blocks.
3249 // Receiving channels need sender reports in order to create
3250 // correct receiver reports.
3251 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003252 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003253 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3254 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255 }
3256
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003257 // If it is a sender report, find the channel that is listening.
3258 bool has_sent_to_default_channel = false;
3259 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003260 int which_channel =
3261 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003262 if (which_channel != -1) {
3263 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003264 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003265
3266 if (IsDefaultChannel(which_channel))
3267 has_sent_to_default_channel = true;
3268 }
3269 }
3270
3271 // SR may continue RR and any RR entry may correspond to any one of the send
3272 // channels. So all RTCP packets must be forwarded all send channels. VoE
3273 // will filter out RR internally.
3274 for (ChannelMap::iterator iter = send_channels_.begin();
3275 iter != send_channels_.end(); ++iter) {
3276 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003277 if (IsDefaultChannel(iter->second->channel()) &&
3278 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003279 continue;
3280
3281 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003282 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003283 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284}
3285
3286bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003287 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3288 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3290 return false;
3291 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003292 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3293 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003294 return false;
3295 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003296 // We set the AGC to mute state only when all the channels are muted.
3297 // This implementation is not ideal, instead we should signal the AGC when
3298 // the mic channel is muted/unmuted. We can't do it today because there
3299 // is no good way to know which stream is mapping to the mic channel.
3300 bool all_muted = muted;
3301 for (ChannelMap::const_iterator iter = send_channels_.begin();
3302 iter != send_channels_.end() && all_muted; ++iter) {
3303 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3304 all_muted)) {
3305 LOG_RTCERR1(GetInputMute, iter->second->channel());
3306 return false;
3307 }
3308 }
3309
3310 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3311 if (ap)
3312 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003313 return true;
3314}
3315
minyue@webrtc.org26236952014-10-29 02:27:08 +00003316// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3317// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003318bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003319 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003320
minyue@webrtc.org26236952014-10-29 02:27:08 +00003321 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003322}
3323
minyue@webrtc.org26236952014-10-29 02:27:08 +00003324bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3325 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003326
minyue@webrtc.org26236952014-10-29 02:27:08 +00003327 send_bitrate_setting_ = true;
3328 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003329
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003330 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003331 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003332 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003333 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003334 }
3335
minyue@webrtc.org26236952014-10-29 02:27:08 +00003336 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003337 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3338 // SetMaxSendBandwith(0), the second call removes the previous limit.
3339 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 return true;
3341
3342 webrtc::CodecInst codec = *send_codec_;
3343 bool is_multi_rate = IsCodecMultiRate(codec);
3344
3345 if (is_multi_rate) {
3346 // If codec is multi-rate then just set the bitrate.
3347 codec.rate = bps;
3348 if (!SetSendCodec(codec)) {
3349 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3350 << " to bitrate " << bps << " bps.";
3351 return false;
3352 }
3353 return true;
3354 } else {
3355 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3356 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3357 // fixed bitrate then ignore.
3358 if (bps < codec.rate) {
3359 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3360 << " to bitrate " << bps << " bps"
3361 << ", requires at least " << codec.rate << " bps.";
3362 return false;
3363 }
3364 return true;
3365 }
3366}
3367
3368bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003369 bool echo_metrics_on = false;
3370 // These can take on valid negative values, so use the lowest possible level
3371 // as default rather than -1.
3372 int echo_return_loss = -100;
3373 int echo_return_loss_enhancement = -100;
3374 // These can also be negative, but in practice -1 is only used to signal
3375 // insufficient data, since the resolution is limited to multiples of 4 ms.
3376 int echo_delay_median_ms = -1;
3377 int echo_delay_std_ms = -1;
3378 if (engine()->voe()->processing()->GetEcMetricsStatus(
3379 echo_metrics_on) != -1 && echo_metrics_on) {
3380 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3381 // here, but it appears to be unsuitable currently. Revisit after this is
3382 // investigated: http://b/issue?id=5666755
3383 int erl, erle, rerl, anlp;
3384 if (engine()->voe()->processing()->GetEchoMetrics(
3385 erl, erle, rerl, anlp) != -1) {
3386 echo_return_loss = erl;
3387 echo_return_loss_enhancement = erle;
3388 }
3389
3390 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003391 float dummy;
3392 if (engine()->voe()->processing()->GetEcDelayMetrics(
3393 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003394 echo_delay_median_ms = median;
3395 echo_delay_std_ms = std;
3396 }
3397 }
3398
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003399 webrtc::CallStatistics cs;
3400 unsigned int ssrc;
3401 webrtc::CodecInst codec;
3402 unsigned int level;
3403
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003404 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3405 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003406 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003408 // Fill in the sender info, based on what we know, and what the
3409 // remote side told us it got from its RTCP report.
3410 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003412 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3413 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3414 continue;
3415 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003417 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003418 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3419 sinfo.bytes_sent = cs.bytesSent;
3420 sinfo.packets_sent = cs.packetsSent;
3421 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3422 // returns 0 to indicate an error value.
3423 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3424
3425 // Get data from the last remote RTCP report. Use default values if no data
3426 // available.
3427 sinfo.fraction_lost = -1.0;
3428 sinfo.jitter_ms = -1;
3429 sinfo.packets_lost = -1;
3430 sinfo.ext_seqnum = -1;
3431 std::vector<webrtc::ReportBlock> receive_blocks;
3432 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3433 channel, &receive_blocks) != -1 &&
3434 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3435 std::vector<webrtc::ReportBlock>::iterator iter;
3436 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3437 ++iter) {
3438 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003439 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003440 // Convert Q8 to floating point.
3441 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3442 // Convert samples to milliseconds.
3443 if (codec.plfreq / 1000 > 0) {
3444 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3445 }
3446 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3447 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3448 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003449 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003450 }
3451 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003452
3453 // Local speech level.
3454 sinfo.audio_level = (engine()->voe()->volume()->
3455 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3456
3457 // TODO(xians): We are injecting the same APM logging to all the send
3458 // channels here because there is no good way to know which send channel
3459 // is using the APM. The correct fix is to allow the send channels to have
3460 // their own APM so that we can feed the correct APM logging to different
3461 // send channels. See issue crbug/264611 .
3462 sinfo.echo_return_loss = echo_return_loss;
3463 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3464 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3465 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003466 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3467 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003468 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003469
3470 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003471 }
3472
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003473 // Build the list of receivers, one for each receiving channel, or 1 in
3474 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003476 for (ChannelMap::const_iterator it = receive_channels_.begin();
3477 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003478 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003479 }
3480 if (channels.empty()) {
3481 channels.push_back(voe_channel());
3482 }
3483
3484 // Get the SSRC and stats for each receiver, based on our own calculations.
3485 for (std::vector<int>::const_iterator it = channels.begin();
3486 it != channels.end(); ++it) {
3487 memset(&cs, 0, sizeof(cs));
3488 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3489 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3490 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3491 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003492 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003493 rinfo.bytes_rcvd = cs.bytesReceived;
3494 rinfo.packets_rcvd = cs.packetsReceived;
3495 // The next four fields are from the most recently sent RTCP report.
3496 // Convert Q8 to floating point.
3497 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3498 rinfo.packets_lost = cs.cumulativeLost;
3499 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003500 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003501 if (codec.pltype != -1) {
3502 rinfo.codec_name = codec.plname;
3503 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003504 // Convert samples to milliseconds.
3505 if (codec.plfreq / 1000 > 0) {
3506 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3507 }
3508
3509 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3510 webrtc::NetworkStatistics ns;
3511 if (engine()->voe()->neteq() &&
3512 engine()->voe()->neteq()->GetNetworkStatistics(
3513 *it, ns) != -1) {
3514 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3515 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3516 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003517 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003518 rinfo.speech_expand_rate =
3519 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3520 rinfo.secondary_decoded_rate =
3521 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003522 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003523
3524 webrtc::AudioDecodingCallStats ds;
3525 if (engine()->voe()->neteq() &&
3526 engine()->voe()->neteq()->GetDecodingCallStatistics(
3527 *it, &ds) != -1) {
3528 rinfo.decoding_calls_to_silence_generator =
3529 ds.calls_to_silence_generator;
3530 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3531 rinfo.decoding_normal = ds.decoded_normal;
3532 rinfo.decoding_plc = ds.decoded_plc;
3533 rinfo.decoding_cng = ds.decoded_cng;
3534 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3535 }
3536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003538 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539 int playout_buffer_delay_ms = 0;
3540 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003541 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3542 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3543 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003544 }
3545
3546 // Get speech level.
3547 rinfo.audio_level = (engine()->voe()->volume()->
3548 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3549 info->receivers.push_back(rinfo);
3550 }
3551 }
3552
3553 return true;
3554}
3555
3556void WebRtcVoiceMediaChannel::GetLastMediaError(
3557 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003558 DCHECK(ssrc != NULL);
3559 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003560 FindSsrc(voe_channel(), ssrc);
3561 *error = WebRtcErrorToChannelError(GetLastEngineError());
3562}
3563
3564bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003565 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003566 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003567 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003568 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3569 // This means the error is not limited to a specific channel. Signal the
3570 // message using ssrc=0. If the current channel is sending, use this
3571 // channel for sending the message.
3572 *ssrc = 0;
3573 return true;
3574 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003575 // Check whether this is a sending channel.
3576 for (ChannelMap::const_iterator it = send_channels_.begin();
3577 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003578 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003579 // This is a sending channel.
3580 uint32 local_ssrc = 0;
3581 if (engine()->voe()->rtp()->GetLocalSSRC(
3582 channel_num, local_ssrc) != -1) {
3583 *ssrc = local_ssrc;
3584 }
3585 return true;
3586 }
3587 }
3588
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003589 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003590 for (ChannelMap::const_iterator it = receive_channels_.begin();
3591 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003592 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003593 *ssrc = it->first;
3594 return true;
3595 }
3596 }
3597 }
3598 return false;
3599}
3600
3601void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003602 if (error == VE_TYPING_NOISE_WARNING) {
3603 typing_noise_detected_ = true;
3604 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3605 typing_noise_detected_ = false;
3606 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003607 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3608}
3609
3610int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3611 unsigned int ulevel;
3612 int ret =
3613 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3614 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3615}
3616
3617int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003618 ChannelMap::iterator it = receive_channels_.find(ssrc);
3619 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003620 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003621 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3622}
3623
3624int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003625 ChannelMap::iterator it = send_channels_.find(ssrc);
3626 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003627 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003628
3629 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003630}
3631
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003632void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3633 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003634 for (const auto& it : receive_channels_) {
3635 TryRemoveAudioRecvStream(it.first);
3636 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003637 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003638 for (const auto& it : receive_channels_) {
3639 TryAddAudioRecvStream(it.first);
3640 }
3641}
3642
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003643bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3644 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3645 // Get the RED encodings from the parameter with no name. This may
3646 // change based on what is discussed on the Jingle list.
3647 // The encoding parameter is of the form "a/b"; we only support where
3648 // a == b. Verify this and parse out the value into red_pt.
3649 // If the parameter value is absent (as it will be until we wire up the
3650 // signaling of this message), use the second codec specified (i.e. the
3651 // one after "red") as the encoding parameter.
3652 int red_pt = -1;
3653 std::string red_params;
3654 CodecParameterMap::const_iterator it = red_codec.params.find("");
3655 if (it != red_codec.params.end()) {
3656 red_params = it->second;
3657 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003658 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003659 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003660 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003661 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3662 return false;
3663 }
3664 } else if (red_codec.params.empty()) {
3665 LOG(LS_WARNING) << "RED params not present, using defaults";
3666 if (all_codecs.size() > 1) {
3667 red_pt = all_codecs[1].id;
3668 }
3669 }
3670
3671 // Try to find red_pt in |codecs|.
3672 std::vector<AudioCodec>::const_iterator codec;
3673 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3674 if (codec->id == red_pt)
3675 break;
3676 }
3677
3678 // If we find the right codec, that will be the codec we pass to
3679 // SetSendCodec, with the desired payload type.
3680 if (codec != all_codecs.end() &&
3681 engine()->FindWebRtcCodec(*codec, send_codec)) {
3682 } else {
3683 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3684 return false;
3685 }
3686
3687 return true;
3688}
3689
3690bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3691 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003692 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003693 return false;
3694 }
3695 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3696 // what we want to do with them.
3697 // engine()->voe().EnableVQMon(voe_channel(), true);
3698 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3699 return true;
3700}
3701
3702bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3703 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3704 for (int i = 0; i < ncodecs; ++i) {
3705 webrtc::CodecInst voe_codec;
3706 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3707 voe_codec.pltype = -1;
3708 if (engine()->voe()->codec()->SetRecPayloadType(
3709 channel, voe_codec) == -1) {
3710 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3711 return false;
3712 }
3713 }
3714 }
3715 return true;
3716}
3717
3718bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3719 if (playout) {
3720 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3721 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3722 LOG_RTCERR1(StartPlayout, channel);
3723 return false;
3724 }
3725 } else {
3726 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3727 engine()->voe()->base()->StopPlayout(channel);
3728 }
3729 return true;
3730}
3731
3732uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3733 bool rtcp) {
3734 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3735 uint32 ssrc = 0;
3736 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003737 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003738 }
3739 return ssrc;
3740}
3741
3742// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3743VoiceMediaChannel::Error
3744 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3745 switch (err_code) {
3746 case 0:
3747 return ERROR_NONE;
3748 case VE_CANNOT_START_RECORDING:
3749 case VE_MIC_VOL_ERROR:
3750 case VE_GET_MIC_VOL_ERROR:
3751 case VE_CANNOT_ACCESS_MIC_VOL:
3752 return ERROR_REC_DEVICE_OPEN_FAILED;
3753 case VE_SATURATION_WARNING:
3754 return ERROR_REC_DEVICE_SATURATION;
3755 case VE_REC_DEVICE_REMOVED:
3756 return ERROR_REC_DEVICE_REMOVED;
3757 case VE_RUNTIME_REC_WARNING:
3758 case VE_RUNTIME_REC_ERROR:
3759 return ERROR_REC_RUNTIME_ERROR;
3760 case VE_CANNOT_START_PLAYOUT:
3761 case VE_SPEAKER_VOL_ERROR:
3762 case VE_GET_SPEAKER_VOL_ERROR:
3763 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3764 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3765 case VE_RUNTIME_PLAY_WARNING:
3766 case VE_RUNTIME_PLAY_ERROR:
3767 return ERROR_PLAY_RUNTIME_ERROR;
3768 case VE_TYPING_NOISE_WARNING:
3769 return ERROR_REC_TYPING_NOISE_DETECTED;
3770 default:
3771 return VoiceMediaChannel::ERROR_OTHER;
3772 }
3773}
3774
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003775bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3776 int channel_id, const RtpHeaderExtension* extension) {
3777 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003778 int id = 0;
3779 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003780 if (extension) {
3781 enable = true;
3782 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003783 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003784 }
3785 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003786 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003787 return false;
3788 }
3789 return true;
3790}
3791
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003792void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3793 DCHECK(thread_checker_.CalledOnValidThread());
3794 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3795 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3796 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3797 webrtc::AudioReceiveStream::Config config;
3798 config.rtp.remote_ssrc = ssrc;
3799 config.rtp.extensions = recv_rtp_extensions_;
3800 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3801 receive_streams_.insert(std::make_pair(ssrc, s));
3802 }
3803}
3804
3805void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3806 DCHECK(thread_checker_.CalledOnValidThread());
3807 // If we are hooked up to a webrtc::Call, assume there is an
3808 // AudioReceiveStream to destroy too.
3809 if (call_) {
3810 auto stream_it = receive_streams_.find(ssrc);
3811 if (stream_it != receive_streams_.end()) {
3812 call_->DestroyAudioReceiveStream(stream_it->second);
3813 receive_streams_.erase(stream_it);
3814 }
3815 }
3816}
3817
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003818int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003819 size_t res = 0;
3820 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003821 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003822}
3823
3824int WebRtcSoundclipStream::Rewind() {
3825 mem_.Rewind();
3826 // Return -1 to keep VoiceEngine from looping.
3827 return (loop_) ? 0 : -1;
3828}
3829
3830} // namespace cricket
3831
3832#endif // HAVE_WEBRTC_VOICE