blob: 62404db9f21d3977a7277ab5824a78569f14f9c0 [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"
56
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
Brave Yao5225dd82015-03-26 07:39:19 +080063static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064struct CodecPref {
65 const char* name;
66 int clockrate;
67 int channels;
68 int payload_type;
69 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080070 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071};
Brave Yao5225dd82015-03-26 07:39:19 +080072// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
75 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
76 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
79 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
80 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
81 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080082 { kCnCodecName, 32000, 1, 106, false, { } },
83 { kCnCodecName, 16000, 1, 105, false, { } },
84 { kCnCodecName, 8000, 1, 13, false, { } },
85 { kRedCodecName, 8000, 1, 127, false, { } },
86 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111// Parameter used for NACK.
112// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
113static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000114
115// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000116// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000117
118// Recommended bitrates:
119// 8-12 kb/s for NB speech,
120// 16-20 kb/s for WB speech,
121// 28-40 kb/s for FB speech,
122// 48-64 kb/s for FB mono music, and
123// 64-128 kb/s for FB stereo music.
124// The current implementation applies the following values to mono signals,
125// and multiplies them by 2 for stereo.
126static const int kOpusBitrateNb = 12000;
127static const int kOpusBitrateWb = 20000;
128static const int kOpusBitrateFb = 32000;
129
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000130// Opus bitrate should be in the range between 6000 and 510000.
131static const int kOpusMinBitrate = 6000;
132static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000133
wu@webrtc.orgde305012013-10-31 15:40:38 +0000134// Default audio dscp value.
135// See http://tools.ietf.org/html/rfc2474 for details.
136// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000137static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000138
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000139// Ensure we open the file in a writeable path on ChromeOS and Android. This
140// workaround can be removed when it's possible to specify a filename for audio
141// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000142//
143// TODO(grunell): Use a string in the options instead of hardcoding it here
144// and let the embedder choose the filename (crbug.com/264223).
145//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000146// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
147// below.
148#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000149static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000150#elif defined(ANDROID)
151static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000152#else
153static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
154#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000155
156// Dumps an AudioCodec in RFC 2327-ish format.
157static std::string ToString(const AudioCodec& codec) {
158 std::stringstream ss;
159 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
160 << " (" << codec.id << ")";
161 return ss.str();
162}
Minyue Li7100dcd2015-03-27 05:05:59 +0100163
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000164static std::string ToString(const webrtc::CodecInst& codec) {
165 std::stringstream ss;
166 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
167 << " (" << codec.pltype << ")";
168 return ss.str();
169}
170
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 const char* delim = "\r\n";
173 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
174 LOG_V(sev) << tok;
175 }
176}
177
178// Severity is an integer because it comes is assumed to be from command line.
179static int SeverityToFilter(int severity) {
180 int filter = webrtc::kTraceNone;
181 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000182 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200184 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000185 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200187 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200190 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000191 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000192 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
193 }
194 return filter;
195}
196
Minyue Li7100dcd2015-03-27 05:05:59 +0100197static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
198 return (_stricmp(codec.name.c_str(), ref_name) == 0);
199}
200
201static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
202 return (_stricmp(codec.plname, ref_name) == 0);
203}
204
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000205static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
206 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100207 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208 kCodecPrefs[i].clockrate == codec.plfreq) {
209 return kCodecPrefs[i].is_multi_rate;
210 }
211 }
212 return false;
213}
214
215static bool FindCodec(const std::vector<AudioCodec>& codecs,
216 const AudioCodec& codec,
217 AudioCodec* found_codec) {
218 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
219 it != codecs.end(); ++it) {
220 if (it->Matches(codec)) {
221 if (found_codec != NULL) {
222 *found_codec = *it;
223 }
224 return true;
225 }
226 }
227 return false;
228}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000229
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000230static bool IsNackEnabled(const AudioCodec& codec) {
231 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
232 kParamValueEmpty));
233}
234
Brave Yao5225dd82015-03-26 07:39:19 +0800235static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
236 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
237 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
238 if (packet_size_ms && packet_size_ms <= ptime_ms) {
239 selected_packet_size_ms = packet_size_ms;
240 }
241 }
242 return selected_packet_size_ms;
243}
244
245// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
246// pacsize if it's valid, or we will pick the next smallest value we support.
247// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
248static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
249 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100250 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800251 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100252 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800253 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
254 if (packet_size_ms) {
255 // Convert unit from milli-seconds to samples.
256 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
257 return true;
258 }
259 }
260 }
261 return false;
262}
263
Minyue Li7100dcd2015-03-27 05:05:59 +0100264// Return true if codec.params[feature] == "1", false otherwise.
265static bool IsCodecFeatureEnabled(const AudioCodec& codec,
266 const char* feature) {
267 int value;
268 return codec.GetParam(feature, &value) && value == 1;
269}
270
271// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
272// otherwise. If the value (either from params or codec.bitrate) <=0, use the
273// default configuration. If the value is beyond feasible bit rate of Opus,
274// clamp it. Returns the Opus bit rate for operation.
275static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
276 int bitrate = 0;
277 bool use_param = true;
278 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
279 bitrate = codec.bitrate;
280 use_param = false;
281 }
282 if (bitrate <= 0) {
283 if (max_playback_rate <= 8000) {
284 bitrate = kOpusBitrateNb;
285 } else if (max_playback_rate <= 16000) {
286 bitrate = kOpusBitrateWb;
287 } else {
288 bitrate = kOpusBitrateFb;
289 }
290
291 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
292 bitrate *= 2;
293 }
294 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
295 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
296 std::string rate_source =
297 use_param ? "Codec parameter \"maxaveragebitrate\"" :
298 "Supplied Opus bitrate";
299 LOG(LS_WARNING) << rate_source
300 << " is invalid and is replaced by: "
301 << bitrate;
302 }
303 return bitrate;
304}
305
306// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
307// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
308static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
309 int value;
310 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
311 return value;
312 }
313 return kOpusDefaultMaxPlaybackRate;
314}
315
316static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
317 bool* enable_codec_fec, int* max_playback_rate,
318 bool* enable_codec_dtx) {
319 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
320 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
321 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
322
323 // If OPUS, change what we send according to the "stereo" codec
324 // parameter, and not the "channels" parameter. We set
325 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
326 // the bitrate is not specified, i.e. is <= zero, we set it to the
327 // appropriate default value for mono or stereo Opus.
328
329 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
330 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
331}
332
333// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
334// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
335// codec.
336static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
337 if (IsCodec(*voe_codec, kG722CodecName)) {
338 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
339 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200340 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100341 voe_codec->plfreq = new_plfreq;
342 }
343}
344
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000345// Gets the default set of options applied to the engine. Historically, these
346// were supplied as a combination of flags from the channel manager (ec, agc,
347// ns, and highpass) and the rest hardcoded in InitInternal.
348static AudioOptions GetDefaultEngineOptions() {
349 AudioOptions options;
350 options.echo_cancellation.Set(true);
351 options.auto_gain_control.Set(true);
352 options.noise_suppression.Set(true);
353 options.highpass_filter.Set(true);
354 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200355 options.audio_jitter_buffer_max_packets.Set(50);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000356 options.typing_detection.Set(true);
357 options.conference_mode.Set(false);
358 options.adjust_agc_delta.Set(0);
359 options.experimental_agc.Set(false);
360 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100361 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000362 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000363 options.aec_dump.Set(false);
364 return options;
365}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366
Minyue Li7100dcd2015-03-27 05:05:59 +0100367static std::string GetEnableString(bool enable) {
368 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800369}
370
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371class WebRtcSoundclipMedia : public SoundclipMedia {
372 public:
373 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
374 : engine_(engine), webrtc_channel_(-1) {
375 engine_->RegisterSoundclip(this);
376 }
377
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +0200378 ~WebRtcSoundclipMedia() override {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379 engine_->UnregisterSoundclip(this);
380 if (webrtc_channel_ != -1) {
381 // We shouldn't have to call Disable() here. DeleteChannel() should call
382 // StopPlayout() while deleting the channel. We should fix the bug
383 // inside WebRTC and remove the Disable() call bellow. This work is
384 // tracked by bug http://b/issue?id=5382855.
385 PlaySound(NULL, 0, 0);
386 Disable();
387 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
388 == -1) {
389 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
390 }
391 }
392 }
393
394 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000395 if (!engine_->voe_sc()) {
396 return false;
397 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000398 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399 if (webrtc_channel_ == -1) {
400 LOG_RTCERR0(CreateChannel);
401 return false;
402 }
403 return true;
404 }
405
406 bool Enable() {
407 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
408 LOG_RTCERR1(StartPlayout, webrtc_channel_);
409 return false;
410 }
411 return true;
412 }
413
414 bool Disable() {
415 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
416 LOG_RTCERR1(StopPlayout, webrtc_channel_);
417 return false;
418 }
419 return true;
420 }
421
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +0200422 bool PlaySound(const char* buf, int len, int flags) override {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000423 // The voe file api is not available in chrome.
424 if (!engine_->voe_sc()->file()) {
425 return false;
426 }
427 // Must stop playing the current sound (if any), because we are about to
428 // modify the stream.
429 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
430 == -1) {
431 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
432 return false;
433 }
434
435 if (buf) {
436 stream_.reset(new WebRtcSoundclipStream(buf, len));
437 stream_->set_loop((flags & SF_LOOP) != 0);
438 stream_->Rewind();
439
440 // Play it.
441 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
442 webrtc_channel_, stream_.get()) == -1) {
443 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
444 LOG(LS_ERROR) << "Unable to start soundclip";
445 return false;
446 }
447 } else {
448 stream_.reset();
449 }
450 return true;
451 }
452
453 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
454
455 private:
456 WebRtcVoiceEngine *engine_;
457 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000459};
460
461WebRtcVoiceEngine::WebRtcVoiceEngine()
462 : voe_wrapper_(new VoEWrapper()),
463 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000464 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465 tracing_(new VoETraceWrapper()),
466 adm_(NULL),
467 adm_sc_(NULL),
468 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
469 is_dumping_aec_(false),
470 desired_local_monitor_enable_(false),
471 tx_processor_ssrc_(0),
472 rx_processor_ssrc_(0) {
473 Construct();
474}
475
476WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
477 VoEWrapper* voe_wrapper_sc,
478 VoETraceWrapper* tracing)
479 : voe_wrapper_(voe_wrapper),
480 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000481 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000482 tracing_(tracing),
483 adm_(NULL),
484 adm_sc_(NULL),
485 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
486 is_dumping_aec_(false),
487 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488 tx_processor_ssrc_(0),
489 rx_processor_ssrc_(0) {
490 Construct();
491}
492
493void WebRtcVoiceEngine::Construct() {
494 SetTraceFilter(log_filter_);
495 initialized_ = false;
496 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
497 SetTraceOptions("");
498 if (tracing_->SetTraceCallback(this) == -1) {
499 LOG_RTCERR0(SetTraceCallback);
500 }
501 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
502 LOG_RTCERR0(RegisterVoiceEngineObserver);
503 }
504 // Clear the default agc state.
505 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
506
507 // Load our audio codec list.
508 ConstructCodecs();
509
510 // Load our RTP Header extensions.
511 rtp_header_extensions_.push_back(
512 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
513 kRtpAudioLevelHeaderExtensionDefaultId));
514 rtp_header_extensions_.push_back(
515 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
516 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
517 options_ = GetDefaultEngineOptions();
518}
519
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000520void WebRtcVoiceEngine::ConstructCodecs() {
521 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
522 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
523 for (int i = 0; i < ncodecs; ++i) {
524 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000525 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000526 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100527 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000528 continue;
529 }
530
531 const CodecPref* pref = NULL;
532 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100533 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000534 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
535 kCodecPrefs[j].channels == voe_codec.channels) {
536 pref = &kCodecPrefs[j];
537 break;
538 }
539 }
540
541 if (pref) {
542 // Use the payload type that we've configured in our pref table;
543 // use the offset in our pref table to determine the sort order.
544 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
545 voe_codec.rate, voe_codec.channels,
546 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
547 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100548 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000549 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000550 codec.bitrate = 0;
551 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100552 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000553 // Only add fmtp parameters that differ from the spec.
554 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
555 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000556 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000557 }
558 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
559 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000560 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000561 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000562 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000563
564 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000565 // when they can be set to values other than the default.
566 }
567 codecs_.push_back(codec);
568 } else {
569 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
570 }
571 }
572 }
573 // Make sure they are in local preference order.
574 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
575}
576
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000577bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
578 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
579 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000580 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000581 // Change the sample rate of G722 to 8000 to match SDP.
582 MaybeFixupG722(codec, 8000);
583 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000584}
585
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000586WebRtcVoiceEngine::~WebRtcVoiceEngine() {
587 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
588 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
589 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
590 }
591 if (adm_) {
592 voe_wrapper_.reset();
593 adm_->Release();
594 adm_ = NULL;
595 }
596 if (adm_sc_) {
597 voe_wrapper_sc_.reset();
598 adm_sc_->Release();
599 adm_sc_ = NULL;
600 }
601
602 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200603 DCHECK(SignalRxMediaFrame.is_empty());
604 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000605
606 tracing_->SetTraceCallback(NULL);
607}
608
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000609bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200610 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000611 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
612 bool res = InitInternal();
613 if (res) {
614 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
615 } else {
616 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
617 Terminate();
618 }
619 return res;
620}
621
622bool WebRtcVoiceEngine::InitInternal() {
623 // Temporarily turn logging level up for the Init call
624 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000625 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000626 SetTraceFilter(extended_filter);
627 SetTraceOptions("");
628
629 // Init WebRtc VoiceEngine.
630 if (voe_wrapper_->base()->Init(adm_) == -1) {
631 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
632 SetTraceFilter(old_filter);
633 return false;
634 }
635
636 SetTraceFilter(old_filter);
637 SetTraceOptions(log_options_);
638
639 // Log the VoiceEngine version info
640 char buffer[1024] = "";
641 voe_wrapper_->base()->GetVersion(buffer);
642 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000643 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644
645 // Save the default AGC configuration settings. This must happen before
646 // calling SetOptions or the default will be overwritten.
647 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
648 LOG_RTCERR0(GetAgcConfig);
649 return false;
650 }
651
652 // Set defaults for options, so that ApplyOptions applies them explicitly
653 // when we clear option (channel) overrides. External clients can still
654 // modify the defaults via SetOptions (on the media engine).
655 if (!SetOptions(GetDefaultEngineOptions())) {
656 return false;
657 }
658
659 // Print our codec list again for the call diagnostic log
660 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
661 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
662 it != codecs_.end(); ++it) {
663 LOG(LS_INFO) << ToString(*it);
664 }
665
666 // Disable the DTMF playout when a tone is sent.
667 // PlayDtmfTone will be used if local playout is needed.
668 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
669 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
670 }
671
672 initialized_ = true;
673 return true;
674}
675
676bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
677 if (voe_wrapper_sc_initialized_) {
678 return true;
679 }
680 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
681 // be false, so subsequent calls to EnsureSoundclipEngineInit will
682 // probably just fail again. That's acceptable behavior.
683#if defined(LINUX) && !defined(HAVE_LIBPULSE)
684 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
685#endif
686
687 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
688 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
689 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
690 return false;
691 }
692
693 // On Windows, tell it to use the default sound (not communication) devices.
694 // First check whether there is a valid sound device for playback.
695 // TODO(juberti): Clean this up when we support setting the soundclip device.
696#ifdef WIN32
697 // The SetPlayoutDevice may not be implemented in the case of external ADM.
698 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
699 // PeerConnection interface never set the adm_sc_, so need to check both
700 // in order to determine if the external adm is used.
701 if (!adm_ && !adm_sc_) {
702 int num_of_devices = 0;
703 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
704 num_of_devices > 0) {
705 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
706 == -1) {
707 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
708 voe_wrapper_sc_->error());
709 return false;
710 }
711 } else {
712 LOG(LS_WARNING) << "No valid sound playout device found.";
713 }
714 }
715#endif
716 voe_wrapper_sc_initialized_ = true;
717 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
718 return true;
719}
720
721void WebRtcVoiceEngine::Terminate() {
722 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
723 initialized_ = false;
724
725 StopAecDump();
726
727 if (voe_wrapper_sc_) {
728 voe_wrapper_sc_initialized_ = false;
729 voe_wrapper_sc_->base()->Terminate();
730 }
731 voe_wrapper_->base()->Terminate();
732 desired_local_monitor_enable_ = false;
733}
734
735int WebRtcVoiceEngine::GetCapabilities() {
736 return AUDIO_SEND | AUDIO_RECV;
737}
738
739VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
740 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
741 if (!ch->valid()) {
742 delete ch;
743 ch = NULL;
744 }
745 return ch;
746}
747
748SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
749 if (!EnsureSoundclipEngineInit()) {
750 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
751 << "initialize.";
752 return NULL;
753 }
754 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
755 if (!soundclip->Init() || !soundclip->Enable()) {
756 delete soundclip;
757 return NULL;
758 }
759 return soundclip;
760}
761
762bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
763 if (!ApplyOptions(options)) {
764 return false;
765 }
766 options_ = options;
767 return true;
768}
769
770bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
771 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
772 if (!ApplyOptions(overrides)) {
773 return false;
774 }
775 option_overrides_ = overrides;
776 return true;
777}
778
779bool WebRtcVoiceEngine::ClearOptionOverrides() {
780 LOG(LS_INFO) << "Clearing option overrides.";
781 AudioOptions options = options_;
782 // Only call ApplyOptions if |options_overrides_| contains overrided options.
783 // ApplyOptions affects NS, AGC other options that is shared between
784 // all WebRtcVoiceEngineChannels.
785 if (option_overrides_ == AudioOptions()) {
786 return true;
787 }
788
789 if (!ApplyOptions(options)) {
790 return false;
791 }
792 option_overrides_ = AudioOptions();
793 return true;
794}
795
796// AudioOptions defaults are set in InitInternal (for options with corresponding
797// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
798bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
799 AudioOptions options = options_in; // The options are modified below.
800 // kEcConference is AEC with high suppression.
801 webrtc::EcModes ec_mode = webrtc::kEcConference;
802 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
803 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
804 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
805 bool aecm_comfort_noise = false;
806 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
807 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
808 << aecm_comfort_noise << " (default is false).";
809 }
810
811#if defined(IOS)
812 // On iOS, VPIO provides built-in EC and AGC.
813 options.echo_cancellation.Set(false);
814 options.auto_gain_control.Set(false);
815#elif defined(ANDROID)
816 ec_mode = webrtc::kEcAecm;
817#endif
818
819#if defined(IOS) || defined(ANDROID)
820 // Set the AGC mode for iOS as well despite disabling it above, to avoid
821 // unsupported configuration errors from webrtc.
822 agc_mode = webrtc::kAgcFixedDigital;
823 options.typing_detection.Set(false);
824 options.experimental_agc.Set(false);
825 options.experimental_aec.Set(false);
826 options.experimental_ns.Set(false);
827#endif
828
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100829 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
830 // where the feature is not supported.
831 bool use_delay_agnostic_aec = false;
832#if !defined(IOS)
833 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
834 if (use_delay_agnostic_aec) {
835 options.echo_cancellation.Set(true);
836 options.experimental_aec.Set(true);
837 ec_mode = webrtc::kEcConference;
838 }
839 }
840#endif
841
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000842 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
843
844 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
845
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000846 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000847 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000848 // Check if platform supports built-in EC. Currently only supported on
849 // Android and in combination with Java based audio layer.
850 // TODO(henrika): investigate possibility to support built-in EC also
851 // in combination with Open SL ES audio.
852 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200853 if (built_in_aec && !use_delay_agnostic_aec) {
854 // Built-in EC exists on this device and use_delay_agnostic_aec is not
855 // overriding it. Enable/Disable it according to the echo_cancellation
856 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200857 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
858 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100859 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000860 // i.e., replace the software EC with the built-in EC.
861 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000862 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000863 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
864 }
865 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000866 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
867 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
868 return false;
869 } else {
870 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
871 << " with mode " << ec_mode;
872 }
873#if !defined(ANDROID)
874 // TODO(ajm): Remove the error return on Android from webrtc.
875 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
876 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
877 return false;
878 }
879#endif
880 if (ec_mode == webrtc::kEcAecm) {
881 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
882 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
883 return false;
884 }
885 }
886 }
887
888 bool auto_gain_control;
889 if (options.auto_gain_control.Get(&auto_gain_control)) {
890 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
891 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
892 return false;
893 } else {
894 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
895 << " with mode " << agc_mode;
896 }
897 }
898
899 if (options.tx_agc_target_dbov.IsSet() ||
900 options.tx_agc_digital_compression_gain.IsSet() ||
901 options.tx_agc_limiter.IsSet()) {
902 // Override default_agc_config_. Generally, an unset option means "leave
903 // the VoE bits alone" in this function, so we want whatever is set to be
904 // stored as the new "default". If we didn't, then setting e.g.
905 // tx_agc_target_dbov would reset digital compression gain and limiter
906 // settings.
907 // Also, if we don't update default_agc_config_, then adjust_agc_delta
908 // would be an offset from the original values, and not whatever was set
909 // explicitly.
910 default_agc_config_.targetLeveldBOv =
911 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
912 default_agc_config_.targetLeveldBOv);
913 default_agc_config_.digitalCompressionGaindB =
914 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
915 default_agc_config_.digitalCompressionGaindB);
916 default_agc_config_.limiterEnable =
917 options.tx_agc_limiter.GetWithDefaultIfUnset(
918 default_agc_config_.limiterEnable);
919 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
920 LOG_RTCERR3(SetAgcConfig,
921 default_agc_config_.targetLeveldBOv,
922 default_agc_config_.digitalCompressionGaindB,
923 default_agc_config_.limiterEnable);
924 return false;
925 }
926 }
927
928 bool noise_suppression;
929 if (options.noise_suppression.Get(&noise_suppression)) {
930 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
931 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
932 return false;
933 } else {
934 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
935 << " with mode " << ns_mode;
936 }
937 }
938
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000939 bool highpass_filter;
940 if (options.highpass_filter.Get(&highpass_filter)) {
941 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
942 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
943 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
944 return false;
945 }
946 }
947
948 bool stereo_swapping;
949 if (options.stereo_swapping.Get(&stereo_swapping)) {
950 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
951 voep->EnableStereoChannelSwapping(stereo_swapping);
952 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
953 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
954 return false;
955 }
956 }
957
Henrik Lundin64dad832015-05-11 12:44:23 +0200958 int audio_jitter_buffer_max_packets;
959 if (options.audio_jitter_buffer_max_packets.Get(
960 &audio_jitter_buffer_max_packets)) {
961 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
962 voe_config_.Set<webrtc::NetEqCapacityConfig>(
963 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
964 }
965
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000966 bool typing_detection;
967 if (options.typing_detection.Get(&typing_detection)) {
968 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
969 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
970 // In case of error, log the info and continue
971 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
972 }
973 }
974
975 int adjust_agc_delta;
976 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
977 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
978 if (!AdjustAgcLevel(adjust_agc_delta)) {
979 return false;
980 }
981 }
982
983 bool aec_dump;
984 if (options.aec_dump.Get(&aec_dump)) {
985 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
986 if (aec_dump)
987 StartAecDump(kAecDumpByAudioOptionFilename);
988 else
989 StopAecDump();
990 }
991
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000992 webrtc::Config config;
993
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100994 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
995 bool delay_agnostic_aec;
996 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
997 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
998 config.Set<webrtc::ReportedDelay>(
999 new webrtc::ReportedDelay(!delay_agnostic_aec));
1000 }
1001
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001002 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001003 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001004 if (experimental_aec_.Get(&experimental_aec)) {
1005 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
1006 config.Set<webrtc::DelayCorrection>(
1007 new webrtc::DelayCorrection(experimental_aec));
1008 }
1009
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001010 experimental_ns_.SetFrom(options.experimental_ns);
1011 bool experimental_ns;
1012 if (experimental_ns_.Get(&experimental_ns)) {
1013 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
1014 config.Set<webrtc::ExperimentalNs>(
1015 new webrtc::ExperimentalNs(experimental_ns));
1016 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001017
1018 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
1019 // returns NULL on audio_processing().
1020 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
1021 if (audioproc) {
1022 audioproc->SetExtraOptions(config);
1023 }
1024
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001025 uint32 recording_sample_rate;
1026 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1027 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1028 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1029 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1030 }
1031 }
1032
1033 uint32 playout_sample_rate;
1034 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1035 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1036 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1037 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1038 }
1039 }
1040
1041 return true;
1042}
1043
1044bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1045 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1046 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1047 LOG_RTCERR1(SetDelayOffsetMs, offset);
1048 return false;
1049 }
1050
1051 return true;
1052}
1053
1054struct ResumeEntry {
1055 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1056 : channel(c),
1057 playout(p),
1058 send(s) {
1059 }
1060
1061 WebRtcVoiceMediaChannel *channel;
1062 bool playout;
1063 SendFlags send;
1064};
1065
1066// TODO(juberti): Refactor this so that the core logic can be used to set the
1067// soundclip device. At that time, reinstate the soundclip pause/resume code.
1068bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1069 const Device* out_device) {
1070#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001071 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001072 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001073 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001074 kDefaultAudioDeviceId;
1075 // The device manager uses -1 as the default device, which was the case for
1076 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1077#ifndef WIN32
1078 if (-1 == in_id) {
1079 in_id = kDefaultAudioDeviceId;
1080 }
1081 if (-1 == out_id) {
1082 out_id = kDefaultAudioDeviceId;
1083 }
1084#endif
1085
1086 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1087 in_device->name : "Default device";
1088 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1089 out_device->name : "Default device";
1090 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1091 << ") and speaker to (id=" << out_id << ", name=" << out_name
1092 << ")";
1093
1094 // If we're running the local monitor, we need to stop it first.
1095 bool ret = true;
1096 if (!PauseLocalMonitor()) {
1097 LOG(LS_WARNING) << "Failed to pause local monitor";
1098 ret = false;
1099 }
1100
1101 // Must also pause all audio playback and capture.
1102 for (ChannelList::const_iterator i = channels_.begin();
1103 i != channels_.end(); ++i) {
1104 WebRtcVoiceMediaChannel *channel = *i;
1105 if (!channel->PausePlayout()) {
1106 LOG(LS_WARNING) << "Failed to pause playout";
1107 ret = false;
1108 }
1109 if (!channel->PauseSend()) {
1110 LOG(LS_WARNING) << "Failed to pause send";
1111 ret = false;
1112 }
1113 }
1114
1115 // Find the recording device id in VoiceEngine and set recording device.
1116 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1117 ret = false;
1118 }
1119 if (ret) {
1120 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1121 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1122 ret = false;
1123 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001124 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1125 if (ap)
1126 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 }
1128
1129 // Find the playout device id in VoiceEngine and set playout device.
1130 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1131 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1132 ret = false;
1133 }
1134 if (ret) {
1135 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001136 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137 ret = false;
1138 }
1139 }
1140
1141 // Resume all audio playback and capture.
1142 for (ChannelList::const_iterator i = channels_.begin();
1143 i != channels_.end(); ++i) {
1144 WebRtcVoiceMediaChannel *channel = *i;
1145 if (!channel->ResumePlayout()) {
1146 LOG(LS_WARNING) << "Failed to resume playout";
1147 ret = false;
1148 }
1149 if (!channel->ResumeSend()) {
1150 LOG(LS_WARNING) << "Failed to resume send";
1151 ret = false;
1152 }
1153 }
1154
1155 // Resume local monitor.
1156 if (!ResumeLocalMonitor()) {
1157 LOG(LS_WARNING) << "Failed to resume local monitor";
1158 ret = false;
1159 }
1160
1161 if (ret) {
1162 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1163 << ") and speaker to (id="<< out_id << " name=" << out_name
1164 << ")";
1165 }
1166
1167 return ret;
1168#else
1169 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001170#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001171}
1172
1173bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1174 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1175 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001176#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177 *rtc_id = dev_id;
1178 return true;
1179#else
1180 // In Windows and Mac, we need to find the VoiceEngine device id by name
1181 // unless the input dev_id is the default device id.
1182 if (kDefaultAudioDeviceId == dev_id) {
1183 *rtc_id = dev_id;
1184 return true;
1185 }
1186
1187 // Get the number of VoiceEngine audio devices.
1188 int count = 0;
1189 if (is_input) {
1190 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1191 LOG_RTCERR0(GetNumOfRecordingDevices);
1192 return false;
1193 }
1194 } else {
1195 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1196 LOG_RTCERR0(GetNumOfPlayoutDevices);
1197 return false;
1198 }
1199 }
1200
1201 for (int i = 0; i < count; ++i) {
1202 char name[128];
1203 char guid[128];
1204 if (is_input) {
1205 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1206 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1207 } else {
1208 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1209 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1210 }
1211
1212 std::string webrtc_name(name);
1213 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1214 *rtc_id = i;
1215 return true;
1216 }
1217 }
1218 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1219 return false;
1220#endif
1221}
1222
1223bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1224 unsigned int ulevel;
1225 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1226 LOG_RTCERR1(GetSpeakerVolume, level);
1227 return false;
1228 }
1229 *level = ulevel;
1230 return true;
1231}
1232
1233bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001234 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1236 LOG_RTCERR1(SetSpeakerVolume, level);
1237 return false;
1238 }
1239 return true;
1240}
1241
1242int WebRtcVoiceEngine::GetInputLevel() {
1243 unsigned int ulevel;
1244 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1245 static_cast<int>(ulevel) : -1;
1246}
1247
1248bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1249 desired_local_monitor_enable_ = enable;
1250 return ChangeLocalMonitor(desired_local_monitor_enable_);
1251}
1252
1253bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1254 // The voe file api is not available in chrome.
1255 if (!voe_wrapper_->file()) {
1256 return false;
1257 }
1258 if (enable && !monitor_) {
1259 monitor_.reset(new WebRtcMonitorStream);
1260 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1261 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1262 // Must call Stop() because there are some cases where Start will report
1263 // failure but still change the state, and if we leave VE in the on state
1264 // then it could crash later when trying to invoke methods on our monitor.
1265 voe_wrapper_->file()->StopRecordingMicrophone();
1266 monitor_.reset();
1267 return false;
1268 }
1269 } else if (!enable && monitor_) {
1270 voe_wrapper_->file()->StopRecordingMicrophone();
1271 monitor_.reset();
1272 }
1273 return true;
1274}
1275
1276bool WebRtcVoiceEngine::PauseLocalMonitor() {
1277 return ChangeLocalMonitor(false);
1278}
1279
1280bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1281 return ChangeLocalMonitor(desired_local_monitor_enable_);
1282}
1283
1284const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1285 return codecs_;
1286}
1287
1288bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1289 return FindWebRtcCodec(in, NULL);
1290}
1291
1292// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1293bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1294 webrtc::CodecInst* out) {
1295 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1296 for (int i = 0; i < ncodecs; ++i) {
1297 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001298 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1300 voe_codec.rate, voe_codec.channels, 0);
1301 bool multi_rate = IsCodecMultiRate(voe_codec);
1302 // Allow arbitrary rates for ISAC to be specified.
1303 if (multi_rate) {
1304 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1305 codec.bitrate = 0;
1306 }
1307 if (codec.Matches(in)) {
1308 if (out) {
1309 // Fixup the payload type.
1310 voe_codec.pltype = in.id;
1311
1312 // Set bitrate if specified.
1313 if (multi_rate && in.bitrate != 0) {
1314 voe_codec.rate = in.bitrate;
1315 }
1316
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001317 // Reset G722 sample rate to 16000 to match WebRTC.
1318 MaybeFixupG722(&voe_codec, 16000);
1319
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001321 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001323 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1325 }
1326 *out = voe_codec;
1327 }
1328 return true;
1329 }
1330 }
1331 }
1332 return false;
1333}
1334const std::vector<RtpHeaderExtension>&
1335WebRtcVoiceEngine::rtp_header_extensions() const {
1336 return rtp_header_extensions_;
1337}
1338
1339void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1340 // if min_sev == -1, we keep the current log level.
1341 if (min_sev >= 0) {
1342 SetTraceFilter(SeverityToFilter(min_sev));
1343 }
1344 log_options_ = filter;
1345 SetTraceOptions(initialized_ ? log_options_ : "");
1346}
1347
1348int WebRtcVoiceEngine::GetLastEngineError() {
1349 return voe_wrapper_->error();
1350}
1351
1352void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1353 log_filter_ = filter;
1354 tracing_->SetTraceFilter(filter);
1355}
1356
1357// We suppport three different logging settings for VoiceEngine:
1358// 1. Observer callback that goes into talk diagnostic logfile.
1359// Use --logfile and --loglevel
1360//
1361// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1362// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1363//
1364// 3. EC log and dump for debugging QualityEngine.
1365// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1366//
1367// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1368// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1369void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1370 // Set encrypted trace file.
1371 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001372 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 std::vector<std::string>::iterator tracefile =
1374 std::find(opts.begin(), opts.end(), "tracefile");
1375 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1376 // Write encrypted debug output (at same loglevel) to file
1377 // EncryptedTraceFile no longer supported.
1378 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1379 LOG_RTCERR1(SetTraceFile, *tracefile);
1380 }
1381 }
1382
wu@webrtc.org97077a32013-10-25 21:18:33 +00001383 // Allow trace options to override the trace filter. We default
1384 // it to log_filter_ (as a translation of libjingle log levels)
1385 // elsewhere, but this allows clients to explicitly set webrtc
1386 // log levels.
1387 std::vector<std::string>::iterator tracefilter =
1388 std::find(opts.begin(), opts.end(), "tracefilter");
1389 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001390 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001391 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1392 }
1393 }
1394
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 // Set AEC dump file
1396 std::vector<std::string>::iterator recordEC =
1397 std::find(opts.begin(), opts.end(), "recordEC");
1398 if (recordEC != opts.end()) {
1399 ++recordEC;
1400 if (recordEC != opts.end())
1401 StartAecDump(recordEC->c_str());
1402 else
1403 StopAecDump();
1404 }
1405}
1406
1407// Ignore spammy trace messages, mostly from the stats API when we haven't
1408// gotten RTCP info yet from the remote side.
1409bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1410 static const char* kTracesToIgnore[] = {
1411 "\tfailed to GetReportBlockInformation",
1412 "GetRecCodec() failed to get received codec",
1413 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1414 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1415 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1416 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1417 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1418 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1419 "SenderInfoReceived No received SR",
1420 "StatisticsRTP() no statistics available",
1421 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1422 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1423 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1424 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1425 NULL
1426 };
1427 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1428 if (trace.find(*p) != std::string::npos) {
1429 return true;
1430 }
1431 }
1432 return false;
1433}
1434
1435void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1436 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001437 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001439 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001441 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001443 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001445 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446
1447 // Skip past boilerplate prefix text
1448 if (length < 72) {
1449 std::string msg(trace, length);
1450 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1451 LOG_V(sev) << msg;
1452 } else {
1453 std::string msg(trace + 71, length - 72);
1454 if (!ShouldIgnoreTrace(msg)) {
1455 LOG_V(sev) << "webrtc: " << msg;
1456 }
1457 }
1458}
1459
1460void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001461 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 WebRtcVoiceMediaChannel* channel = NULL;
1463 uint32 ssrc = 0;
1464 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1465 << channel_num << ".";
1466 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001467 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468 channel->OnError(ssrc, err_code);
1469 } else {
1470 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1471 << " could not be found in channel list when error reported.";
1472 }
1473}
1474
1475bool WebRtcVoiceEngine::FindChannelAndSsrc(
1476 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001477 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478
1479 *channel = NULL;
1480 *ssrc = 0;
1481 // Find corresponding channel and ssrc
1482 for (ChannelList::const_iterator it = channels_.begin();
1483 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001484 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 if ((*it)->FindSsrc(channel_num, ssrc)) {
1486 *channel = *it;
1487 return true;
1488 }
1489 }
1490
1491 return false;
1492}
1493
1494// This method will search through the WebRtcVoiceMediaChannels and
1495// obtain the voice engine's channel number.
1496bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1497 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001498 DCHECK(channel_num != NULL);
1499 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500
1501 *channel_num = -1;
1502 // Find corresponding channel for ssrc.
1503 for (ChannelList::const_iterator it = channels_.begin();
1504 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001505 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506 if (direction & MPD_RX) {
1507 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1508 }
1509 if (*channel_num == -1 && (direction & MPD_TX)) {
1510 *channel_num = (*it)->GetSendChannelNum(ssrc);
1511 }
1512 if (*channel_num != -1) {
1513 return true;
1514 }
1515 }
1516 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1517 return false;
1518}
1519
1520void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001521 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522 channels_.push_back(channel);
1523}
1524
1525void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001526 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527 ChannelList::iterator i = std::find(channels_.begin(),
1528 channels_.end(),
1529 channel);
1530 if (i != channels_.end()) {
1531 channels_.erase(i);
1532 }
1533}
1534
1535void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1536 soundclips_.push_back(soundclip);
1537}
1538
1539void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1540 SoundclipList::iterator i = std::find(soundclips_.begin(),
1541 soundclips_.end(),
1542 soundclip);
1543 if (i != soundclips_.end()) {
1544 soundclips_.erase(i);
1545 }
1546}
1547
1548// Adjusts the default AGC target level by the specified delta.
1549// NB: If we start messing with other config fields, we'll want
1550// to save the current webrtc::AgcConfig as well.
1551bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1552 webrtc::AgcConfig config = default_agc_config_;
1553 config.targetLeveldBOv -= delta;
1554
1555 LOG(LS_INFO) << "Adjusting AGC level from default -"
1556 << default_agc_config_.targetLeveldBOv << "dB to -"
1557 << config.targetLeveldBOv << "dB";
1558
1559 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1560 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1561 return false;
1562 }
1563 return true;
1564}
1565
1566bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1567 webrtc::AudioDeviceModule* adm_sc) {
1568 if (initialized_) {
1569 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1570 return false;
1571 }
1572 if (adm_) {
1573 adm_->Release();
1574 adm_ = NULL;
1575 }
1576 if (adm) {
1577 adm_ = adm;
1578 adm_->AddRef();
1579 }
1580
1581 if (adm_sc_) {
1582 adm_sc_->Release();
1583 adm_sc_ = NULL;
1584 }
1585 if (adm_sc) {
1586 adm_sc_ = adm_sc;
1587 adm_sc_->AddRef();
1588 }
1589 return true;
1590}
1591
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001592bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1593 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001594 if (!aec_dump_file_stream) {
1595 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001596 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001597 LOG(LS_WARNING) << "Could not close file.";
1598 return false;
1599 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001600 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001601 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001602 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001603 LOG_RTCERR0(StartDebugRecording);
1604 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001605 return false;
1606 }
1607 is_dumping_aec_ = true;
1608 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001609}
1610
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001611bool WebRtcVoiceEngine::RegisterProcessor(
1612 uint32 ssrc,
1613 VoiceProcessor* voice_processor,
1614 MediaProcessorDirection direction) {
1615 bool register_with_webrtc = false;
1616 int channel_id = -1;
1617 bool success = false;
1618 uint32* processor_ssrc = NULL;
1619 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1620 if (voice_processor == NULL || !found_channel) {
1621 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1622 << " foundChannel: " << found_channel;
1623 return false;
1624 }
1625
1626 webrtc::ProcessingTypes processing_type;
1627 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001628 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001629 if (direction == MPD_RX) {
1630 processing_type = webrtc::kPlaybackAllChannelsMixed;
1631 if (SignalRxMediaFrame.is_empty()) {
1632 register_with_webrtc = true;
1633 processor_ssrc = &rx_processor_ssrc_;
1634 }
1635 SignalRxMediaFrame.connect(voice_processor,
1636 &VoiceProcessor::OnFrame);
1637 } else {
1638 processing_type = webrtc::kRecordingPerChannel;
1639 if (SignalTxMediaFrame.is_empty()) {
1640 register_with_webrtc = true;
1641 processor_ssrc = &tx_processor_ssrc_;
1642 }
1643 SignalTxMediaFrame.connect(voice_processor,
1644 &VoiceProcessor::OnFrame);
1645 }
1646 }
1647 if (register_with_webrtc) {
1648 // TODO(janahan): when registering consider instantiating a
1649 // a VoeMediaProcess object and not make the engine extend the interface.
1650 if (voe()->media() && voe()->media()->
1651 RegisterExternalMediaProcessing(channel_id,
1652 processing_type,
1653 *this) != -1) {
1654 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1655 << channel_id;
1656 *processor_ssrc = ssrc;
1657 success = true;
1658 } else {
1659 LOG_RTCERR2(RegisterExternalMediaProcessing,
1660 channel_id,
1661 processing_type);
1662 success = false;
1663 }
1664 } else {
1665 // If we don't have to register with the engine, we just needed to
1666 // connect a new processor, set success to true;
1667 success = true;
1668 }
1669 return success;
1670}
1671
1672bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1673 MediaProcessorDirection channel_direction,
1674 uint32 ssrc,
1675 VoiceProcessor* voice_processor,
1676 MediaProcessorDirection processor_direction) {
1677 bool success = true;
1678 FrameSignal* signal;
1679 webrtc::ProcessingTypes processing_type;
1680 uint32* processor_ssrc = NULL;
1681 if (channel_direction == MPD_RX) {
1682 signal = &SignalRxMediaFrame;
1683 processing_type = webrtc::kPlaybackAllChannelsMixed;
1684 processor_ssrc = &rx_processor_ssrc_;
1685 } else {
1686 signal = &SignalTxMediaFrame;
1687 processing_type = webrtc::kRecordingPerChannel;
1688 processor_ssrc = &tx_processor_ssrc_;
1689 }
1690
1691 int deregister_id = -1;
1692 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001693 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1695 signal->disconnect(voice_processor);
1696 int channel_id = -1;
1697 bool found_channel = FindChannelNumFromSsrc(ssrc,
1698 channel_direction,
1699 &channel_id);
1700 if (signal->is_empty() && found_channel) {
1701 deregister_id = channel_id;
1702 }
1703 }
1704 }
1705 if (deregister_id != -1) {
1706 if (voe()->media() &&
1707 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1708 processing_type) != -1) {
1709 *processor_ssrc = 0;
1710 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1711 << deregister_id;
1712 } else {
1713 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1714 deregister_id,
1715 processing_type);
1716 success = false;
1717 }
1718 }
1719 return success;
1720}
1721
1722bool WebRtcVoiceEngine::UnregisterProcessor(
1723 uint32 ssrc,
1724 VoiceProcessor* voice_processor,
1725 MediaProcessorDirection direction) {
1726 bool success = true;
1727 if (voice_processor == NULL) {
1728 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1729 << ssrc;
1730 return false;
1731 }
1732 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1733 success = false;
1734 }
1735 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1736 success = false;
1737 }
1738 return success;
1739}
1740
1741// Implementing method from WebRtc VoEMediaProcess interface
1742// Do not lock mux_channel_cs_ in this callback.
1743void WebRtcVoiceEngine::Process(int channel,
1744 webrtc::ProcessingTypes type,
1745 int16_t audio10ms[],
1746 int length,
1747 int sampling_freq,
1748 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001749 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1751 if (type == webrtc::kPlaybackAllChannelsMixed) {
1752 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1753 } else if (type == webrtc::kRecordingPerChannel) {
1754 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1755 } else {
1756 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1757 << " channel: " << channel << " type: " << type
1758 << " tx_ssrc: " << tx_processor_ssrc_
1759 << " rx_ssrc: " << rx_processor_ssrc_;
1760 }
1761}
1762
1763void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1764 if (!is_dumping_aec_) {
1765 // Start dumping AEC when we are not dumping.
1766 if (voe_wrapper_->processing()->StartDebugRecording(
1767 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001768 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 } else {
1770 is_dumping_aec_ = true;
1771 }
1772 }
1773}
1774
1775void WebRtcVoiceEngine::StopAecDump() {
1776 if (is_dumping_aec_) {
1777 // Stop dumping AEC when we are dumping.
1778 if (voe_wrapper_->processing()->StopDebugRecording() !=
1779 webrtc::AudioProcessing::kNoError) {
1780 LOG_RTCERR0(StopDebugRecording);
1781 }
1782 is_dumping_aec_ = false;
1783 }
1784}
1785
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001786int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001787 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001788}
1789
1790int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1791 return CreateVoiceChannel(voe_wrapper_.get());
1792}
1793
1794int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1795 return CreateVoiceChannel(voe_wrapper_sc_.get());
1796}
1797
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001798class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1799 : public AudioRenderer::Sink {
1800 public:
1801 WebRtcVoiceChannelRenderer(int ch,
1802 webrtc::AudioTransport* voe_audio_transport)
1803 : channel_(ch),
1804 voe_audio_transport_(voe_audio_transport),
1805 renderer_(NULL) {
1806 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001807 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001808
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001809 // Starts the rendering by setting a sink to the renderer to get data
1810 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001811 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001812 // TODO(xians): Make sure Start() is called only once.
1813 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001814 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001815 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001816 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001817 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001818 return;
1819 }
1820
1821 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1822 // in getUserMedia by default.
1823 renderer->AddChannel(channel_);
1824 renderer->SetSink(this);
1825 renderer_ = renderer;
1826 }
1827
1828 // Stops rendering by setting the sink of the renderer to NULL. No data
1829 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001830 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001831 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001832 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001833 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001834 return;
1835
1836 renderer_->RemoveChannel(channel_);
1837 renderer_->SetSink(NULL);
1838 renderer_ = NULL;
1839 }
1840
1841 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001842 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001843 void OnData(const void* audio_data,
1844 int bits_per_sample,
1845 int sample_rate,
1846 int number_of_channels,
1847 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001848 voe_audio_transport_->OnData(channel_,
1849 audio_data,
1850 bits_per_sample,
1851 sample_rate,
1852 number_of_channels,
1853 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001854 }
1855
1856 // Callback from the |renderer_| when it is going away. In case Start() has
1857 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001858 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001859 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001860 // Set |renderer_| to NULL to make sure no more callback will get into
1861 // the renderer.
1862 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001863 }
1864
1865 // Accessor to the VoE channel ID.
1866 int channel() const { return channel_; }
1867
1868 private:
1869 const int channel_;
1870 webrtc::AudioTransport* const voe_audio_transport_;
1871
1872 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1873 // PeerConnection will make sure invalidating the pointer before the object
1874 // goes away.
1875 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001876
1877 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001878 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001879};
1880
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001882WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1883 : engine_(engine),
1884 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001885 send_bitrate_setting_(false),
1886 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 options_(),
1888 dtmf_allowed_(false),
1889 desired_playout_(false),
1890 nack_enabled_(false),
1891 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001892 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 desired_send_(SEND_NOTHING),
1894 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001895 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 default_receive_ssrc_(0) {
1897 engine->RegisterChannel(this);
1898 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1899 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001900 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901}
1902
1903WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1904 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1905 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001906 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001908 // Remove any remaining send streams, the default channel will be deleted
1909 // later.
1910 while (!send_channels_.empty())
1911 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912
1913 // Unregister ourselves from the engine.
1914 engine()->UnregisterChannel(this);
1915 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001916 while (!receive_channels_.empty()) {
1917 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001919 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001921 // Delete the default channel.
1922 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001923}
1924
1925bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1926 LOG(LS_INFO) << "Setting voice channel options: "
1927 << options.ToString();
1928
wu@webrtc.orgde305012013-10-31 15:40:38 +00001929 // Check if DSCP value is changed from previous.
1930 bool dscp_option_changed = (options_.dscp != options.dscp);
1931
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001932 // TODO(xians): Add support to set different options for different send
1933 // streams after we support multiple APMs.
1934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 // We retain all of the existing options, and apply the given ones
1936 // on top. This means there is no way to "clear" options such that
1937 // they go back to the engine default.
1938 options_.SetAll(options);
1939
1940 if (send_ != SEND_NOTHING) {
1941 if (!engine()->SetOptionOverrides(options_)) {
1942 LOG(LS_WARNING) <<
1943 "Failed to engine SetOptionOverrides during channel SetOptions.";
1944 return false;
1945 }
1946 } else {
1947 // Will be interpreted when appropriate.
1948 }
1949
wu@webrtc.org97077a32013-10-25 21:18:33 +00001950 // Receiver-side auto gain control happens per channel, so set it here from
1951 // options. Note that, like conference mode, setting it on the engine won't
1952 // have the desired effect, since voice channels don't inherit options from
1953 // the media engine when those options are applied per-channel.
1954 bool rx_auto_gain_control;
1955 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1956 if (engine()->voe()->processing()->SetRxAgcStatus(
1957 voe_channel(), rx_auto_gain_control,
1958 webrtc::kAgcFixedDigital) == -1) {
1959 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1960 return false;
1961 } else {
1962 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1963 << " with mode " << webrtc::kAgcFixedDigital;
1964 }
1965 }
1966 if (options.rx_agc_target_dbov.IsSet() ||
1967 options.rx_agc_digital_compression_gain.IsSet() ||
1968 options.rx_agc_limiter.IsSet()) {
1969 webrtc::AgcConfig config;
1970 // If only some of the options are being overridden, get the current
1971 // settings for the channel and bail if they aren't available.
1972 if (!options.rx_agc_target_dbov.IsSet() ||
1973 !options.rx_agc_digital_compression_gain.IsSet() ||
1974 !options.rx_agc_limiter.IsSet()) {
1975 if (engine()->voe()->processing()->GetRxAgcConfig(
1976 voe_channel(), config) != 0) {
1977 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1978 << "channel " << voe_channel() << ". Since not all rx "
1979 << "agc options are specified, unable to safely set rx "
1980 << "agc options.";
1981 return false;
1982 }
1983 }
1984 config.targetLeveldBOv =
1985 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1986 config.targetLeveldBOv);
1987 config.digitalCompressionGaindB =
1988 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1989 config.digitalCompressionGaindB);
1990 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1991 config.limiterEnable);
1992 if (engine()->voe()->processing()->SetRxAgcConfig(
1993 voe_channel(), config) == -1) {
1994 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1995 config.digitalCompressionGaindB, config.limiterEnable);
1996 return false;
1997 }
1998 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001999 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002000 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002001 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002002 dscp = kAudioDscpValue;
2003 if (MediaChannel::SetDscp(dscp) != 0) {
2004 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
2005 }
2006 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00002007
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002008 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002009
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 LOG(LS_INFO) << "Set voice channel options. Current options: "
2011 << options_.ToString();
2012 return true;
2013}
2014
2015bool WebRtcVoiceMediaChannel::SetRecvCodecs(
2016 const std::vector<AudioCodec>& codecs) {
2017 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018 LOG(LS_INFO) << "Setting receive voice codecs:";
2019
2020 std::vector<AudioCodec> new_codecs;
2021 // Find all new codecs. We allow adding new codecs but don't allow changing
2022 // the payload type of codecs that is already configured since we might
2023 // already be receiving packets with that payload type.
2024 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002025 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 AudioCodec old_codec;
2027 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2028 if (old_codec.id != it->id) {
2029 LOG(LS_ERROR) << it->name << " payload type changed.";
2030 return false;
2031 }
2032 } else {
2033 new_codecs.push_back(*it);
2034 }
2035 }
2036 if (new_codecs.empty()) {
2037 // There are no new codecs to configure. Already configured codecs are
2038 // never removed.
2039 return true;
2040 }
2041
2042 if (playout_) {
2043 // Receive codecs can not be changed while playing. So we temporarily
2044 // pause playout.
2045 PausePlayout();
2046 }
2047
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002048 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2050 it != new_codecs.end() && ret; ++it) {
2051 webrtc::CodecInst voe_codec;
2052 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2053 LOG(LS_INFO) << ToString(*it);
2054 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002055 if (default_receive_ssrc_ == 0) {
2056 // Set the receive codecs on the default channel explicitly if the
2057 // default channel is not used by |receive_channels_|, this happens in
2058 // conference mode or in non-conference mode when there is no playout
2059 // channel.
2060 // TODO(xians): Figure out how we use the default channel in conference
2061 // mode.
2062 if (engine()->voe()->codec()->SetRecPayloadType(
2063 voe_channel(), voe_codec) == -1) {
2064 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2065 ret = false;
2066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 }
2068
2069 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002070 for (ChannelMap::iterator it = receive_channels_.begin();
2071 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002073 it->second->channel(), voe_codec) == -1) {
2074 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002075 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 ret = false;
2077 }
2078 }
2079 } else {
2080 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2081 ret = false;
2082 }
2083 }
2084 if (ret) {
2085 recv_codecs_ = codecs;
2086 }
2087
2088 if (desired_playout_ && !playout_) {
2089 ResumePlayout();
2090 }
2091 return ret;
2092}
2093
2094bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002095 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002096 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002097 engine()->voe()->codec()->SetVADStatus(channel, false);
2098 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002099 engine()->voe()->rtp()->SetREDStatus(channel, false);
2100 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101
2102 // Scan through the list to figure out the codec to use for sending, along
2103 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002104 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105 webrtc::CodecInst send_codec;
2106 memset(&send_codec, 0, sizeof(send_codec));
2107
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002108 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002109 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01002110 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00002111 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002112
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002113 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2115 it != codecs.end(); ++it) {
2116 // Ignore codecs we don't know about. The negotiation step should prevent
2117 // this, but double-check to be sure.
2118 webrtc::CodecInst voe_codec;
2119 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002120 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 continue;
2122 }
2123
Minyue Li7100dcd2015-03-27 05:05:59 +01002124 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002125 // Skip telephone-event/CN codec, which will be handled later.
2126 continue;
2127 }
2128
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002129 // We'll use the first codec in the list to actually send audio data.
2130 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002131 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002132 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01002133 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002134 // Parse out the RED parameters. If we fail, just ignore RED;
2135 // we don't support all possible params/usage scenarios.
2136 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2137 continue;
2138 }
2139
2140 // Enable redundant encoding of the specified codec. Treat any
2141 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002142 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2143 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2144 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002145 return false;
2146 }
2147 } else {
2148 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002149 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01002150 // For Opus as the send codec, we are to determine inband FEC, maximum
2151 // playback rate, and opus internal dtx.
2152 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002153 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01002154 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002155 }
Brave Yao5225dd82015-03-26 07:39:19 +08002156
2157 // Set packet size if the AudioCodec param kCodecParamPTime is set.
2158 int ptime_ms = 0;
2159 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
2160 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2161 LOG(LS_WARNING) << "Failed to set packet size for codec "
2162 << send_codec.plname;
2163 return false;
2164 }
2165 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002166 }
2167 found_send_codec = true;
2168 break;
2169 }
2170
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002171 if (nack_enabled_ != nack_enabled) {
2172 SetNack(channel, nack_enabled);
2173 nack_enabled_ = nack_enabled;
2174 }
2175
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002176 if (!found_send_codec) {
2177 LOG(LS_WARNING) << "Received empty list of codecs.";
2178 return false;
2179 }
2180
2181 // Set the codec immediately, since SetVADStatus() depends on whether
2182 // the current codec is mono or stereo.
2183 if (!SetSendCodec(channel, send_codec))
2184 return false;
2185
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002186 // FEC should be enabled after SetSendCodec.
2187 if (enable_codec_fec) {
2188 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2189 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002190 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2191 // Enable codec internal FEC. Treat any failure as fatal internal error.
2192 LOG_RTCERR2(SetFECStatus, channel, true);
2193 return false;
2194 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002195 }
2196
Minyue Li7100dcd2015-03-27 05:05:59 +01002197 if (IsCodec(send_codec, kOpusCodecName)) {
2198 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2199 // send codec has to be Opus.
2200
2201 // Set Opus internal DTX.
2202 LOG(LS_INFO) << "Attempt to "
2203 << GetEnableString(enable_opus_dtx)
2204 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002205 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002206 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2207 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2208 return false;
2209 }
2210
2211 // If opus_max_playback_rate <= 0, the default maximum playback rate
2212 // (48 kHz) will be used.
2213 if (opus_max_playback_rate > 0) {
2214 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2215 << opus_max_playback_rate
2216 << " Hz on channel "
2217 << channel;
2218 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2219 channel, opus_max_playback_rate) == -1) {
2220 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2221 return false;
2222 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002223 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002224 }
2225
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002226 // Always update the |send_codec_| to the currently set send codec.
2227 send_codec_.reset(new webrtc::CodecInst(send_codec));
2228
minyue@webrtc.org26236952014-10-29 02:27:08 +00002229 if (send_bitrate_setting_) {
2230 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002231 }
2232
2233 // Loop through the codecs list again to config the telephone-event/CN codec.
2234 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2235 it != codecs.end(); ++it) {
2236 // Ignore codecs we don't know about. The negotiation step should prevent
2237 // this, but double-check to be sure.
2238 webrtc::CodecInst voe_codec;
2239 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2240 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2241 continue;
2242 }
2243
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002244 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2245 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002246 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002247 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2248 channel, it->id) == -1) {
2249 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2250 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002251 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002252 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002253 // Turn voice activity detection/comfort noise on if supported.
2254 // Set the wideband CN payload type appropriately.
2255 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 webrtc::PayloadFrequencies cn_freq;
2257 switch (it->clockrate) {
2258 case 8000:
2259 cn_freq = webrtc::kFreq8000Hz;
2260 break;
2261 case 16000:
2262 cn_freq = webrtc::kFreq16000Hz;
2263 break;
2264 case 32000:
2265 cn_freq = webrtc::kFreq32000Hz;
2266 break;
2267 default:
2268 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2269 << " not supported.";
2270 continue;
2271 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002272 // Set the CN payloadtype and the VAD status.
2273 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2274 if (cn_freq != webrtc::kFreq8000Hz) {
2275 if (engine()->voe()->codec()->SetSendCNPayloadType(
2276 channel, it->id, cn_freq) == -1) {
2277 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2278 // TODO(ajm): This failure condition will be removed from VoE.
2279 // Restore the return here when we update to a new enough webrtc.
2280 //
2281 // Not returning false because the SetSendCNPayloadType will fail if
2282 // the channel is already sending.
2283 // This can happen if the remote description is applied twice, for
2284 // example in the case of ROAP on top of JSEP, where both side will
2285 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002286 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002287 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002288 // Only turn on VAD if we have a CN payload type that matches the
2289 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002290 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2291 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2292 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002293 LOG(LS_INFO) << "Enabling VAD";
2294 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2295 LOG_RTCERR2(SetVADStatus, channel, true);
2296 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 }
2298 }
2299 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002300 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002301 return true;
2302}
2303
2304bool WebRtcVoiceMediaChannel::SetSendCodecs(
2305 const std::vector<AudioCodec>& codecs) {
2306 dtmf_allowed_ = false;
2307 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2308 it != codecs.end(); ++it) {
2309 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002310 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002311 dtmf_allowed_ = true;
2312 }
2313 }
2314
2315 // Cache the codecs in order to configure the channel created later.
2316 send_codecs_ = codecs;
2317 for (ChannelMap::iterator iter = send_channels_.begin();
2318 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002319 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002320 return false;
2321 }
2322 }
2323
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002324 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002325 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 return true;
2327}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002328
2329void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2330 bool nack_enabled) {
2331 for (ChannelMap::const_iterator it = channels.begin();
2332 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002333 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002334 }
2335}
2336
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002337void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002339 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2341 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002342 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002343 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2344 }
2345}
2346
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347bool WebRtcVoiceMediaChannel::SetSendCodec(
2348 const webrtc::CodecInst& send_codec) {
2349 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2350 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002351 for (ChannelMap::iterator iter = send_channels_.begin();
2352 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002353 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002354 return false;
2355 }
2356
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002357 return true;
2358}
2359
2360bool WebRtcVoiceMediaChannel::SetSendCodec(
2361 int channel, const webrtc::CodecInst& send_codec) {
2362 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2363 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2364
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002365 webrtc::CodecInst current_codec;
2366 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2367 (send_codec == current_codec)) {
2368 // Codec is already configured, we can return without setting it again.
2369 return true;
2370 }
2371
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002372 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2373 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 return false;
2375 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 return true;
2377}
2378
2379bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2380 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002381 if (receive_extensions_ == extensions) {
2382 return true;
2383 }
2384
2385 // The default channel may or may not be in |receive_channels_|. Set the rtp
2386 // header extensions for default channel regardless.
2387 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2388 return false;
2389 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002390
2391 // Loop through all receive channels and enable/disable the extensions.
2392 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2393 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002394 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2395 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002396 return false;
2397 }
2398 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002399
2400 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002401
2402 // Recreate AudioReceiveStream:s.
2403 {
2404 std::vector<webrtc::RtpExtension> exts;
2405
2406 const RtpHeaderExtension* audio_level_extension =
2407 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2408 if (audio_level_extension) {
2409 exts.push_back({
2410 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2411 }
2412
2413 const RtpHeaderExtension* send_time_extension =
2414 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2415 if (send_time_extension) {
2416 exts.push_back({
2417 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2418 }
2419
2420 recv_rtp_extensions_.swap(exts);
2421 SetCall(call_);
2422 }
2423
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002424 return true;
2425}
2426
2427bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2428 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002429 const RtpHeaderExtension* audio_level_extension =
2430 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2431 if (!SetHeaderExtension(
2432 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2433 audio_level_extension)) {
2434 return false;
2435 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002436
2437 const RtpHeaderExtension* send_time_extension =
2438 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2439 if (!SetHeaderExtension(
2440 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2441 send_time_extension)) {
2442 return false;
2443 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002444
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 return true;
2446}
2447
2448bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2449 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002450 if (send_extensions_ == extensions) {
2451 return true;
2452 }
2453
2454 // The default channel may or may not be in |send_channels_|. Set the rtp
2455 // header extensions for default channel regardless.
2456
2457 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2458 return false;
2459 }
2460
2461 // Loop through all send channels and enable/disable the extensions.
2462 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2463 channel_it != send_channels_.end(); ++channel_it) {
2464 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2465 extensions)) {
2466 return false;
2467 }
2468 }
2469
2470 send_extensions_ = extensions;
2471 return true;
2472}
2473
2474bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2475 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002476 const RtpHeaderExtension* audio_level_extension =
2477 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002478
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002479 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002480 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002481 audio_level_extension)) {
2482 return false;
2483 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002484
2485 const RtpHeaderExtension* send_time_extension =
2486 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002487 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002488 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002489 send_time_extension)) {
2490 return false;
2491 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 return true;
2494}
2495
2496bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2497 desired_playout_ = playout;
2498 return ChangePlayout(desired_playout_);
2499}
2500
2501bool WebRtcVoiceMediaChannel::PausePlayout() {
2502 return ChangePlayout(false);
2503}
2504
2505bool WebRtcVoiceMediaChannel::ResumePlayout() {
2506 return ChangePlayout(desired_playout_);
2507}
2508
2509bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2510 if (playout_ == playout) {
2511 return true;
2512 }
2513
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002514 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002516 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517 // Only toggle the default channel if we don't have any other channels.
2518 result = SetPlayout(voe_channel(), playout);
2519 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002520 for (ChannelMap::iterator it = receive_channels_.begin();
2521 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002522 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002523 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002524 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002525 result = false;
2526 }
2527 }
2528
2529 if (result) {
2530 playout_ = playout;
2531 }
2532 return result;
2533}
2534
2535bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2536 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002537 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002538 return ChangeSend(desired_send_);
2539 return true;
2540}
2541
2542bool WebRtcVoiceMediaChannel::PauseSend() {
2543 return ChangeSend(SEND_NOTHING);
2544}
2545
2546bool WebRtcVoiceMediaChannel::ResumeSend() {
2547 return ChangeSend(desired_send_);
2548}
2549
2550bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2551 if (send_ == send) {
2552 return true;
2553 }
2554
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002555 // Change the settings on each send channel.
2556 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002557 engine()->SetOptionOverrides(options_);
2558
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002559 // Change the settings on each send channel.
2560 for (ChannelMap::iterator iter = send_channels_.begin();
2561 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002562 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002564 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002565
2566 // Clear up the options after stopping sending.
2567 if (send == SEND_NOTHING)
2568 engine()->ClearOptionOverrides();
2569
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570 send_ = send;
2571 return true;
2572}
2573
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002574bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2575 if (send == SEND_MICROPHONE) {
2576 if (engine()->voe()->base()->StartSend(channel) == -1) {
2577 LOG_RTCERR1(StartSend, channel);
2578 return false;
2579 }
2580 if (engine()->voe()->file() &&
2581 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2582 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2583 return false;
2584 }
2585 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002586 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002587 if (engine()->voe()->base()->StopSend(channel) == -1) {
2588 LOG_RTCERR1(StopSend, channel);
2589 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002590 }
2591 }
2592
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return true;
2594}
2595
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002596// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002597void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2598 if (engine()->voe()->network()->RegisterExternalTransport(
2599 channel, *this) == -1) {
2600 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2601 }
2602
2603 // Enable RTCP (for quality stats and feedback messages)
2604 EnableRtcp(channel);
2605
2606 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2607 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002608
2609 // Set RTP header extension for the new channel.
2610 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002611}
2612
2613bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2614 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2615 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2616 }
2617
2618 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2619 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 return false;
2621 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002622
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002623 return true;
2624}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002625
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2627 // If the default channel is already used for sending create a new channel
2628 // otherwise use the default channel for sending.
2629 int channel = GetSendChannelNum(sp.first_ssrc());
2630 if (channel != -1) {
2631 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2632 return false;
2633 }
2634
2635 bool default_channel_is_available = true;
2636 for (ChannelMap::const_iterator iter = send_channels_.begin();
2637 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002638 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002639 default_channel_is_available = false;
2640 break;
2641 }
2642 }
2643 if (default_channel_is_available) {
2644 channel = voe_channel();
2645 } else {
2646 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002647 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002648 if (channel == -1) {
2649 LOG_RTCERR0(CreateChannel);
2650 return false;
2651 }
2652
2653 ConfigureSendChannel(channel);
2654 }
2655
2656 // Save the channel to send_channels_, so that RemoveSendStream() can still
2657 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002658 webrtc::AudioTransport* audio_transport =
2659 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002660 send_channels_.insert(std::make_pair(
2661 sp.first_ssrc(),
2662 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002663
2664 // Set the send (local) SSRC.
2665 // If there are multiple send SSRCs, we can only set the first one here, and
2666 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2667 // (with a codec requires multiple SSRC(s)).
2668 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2669 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2670 return false;
2671 }
2672
2673 // At this point the channel's local SSRC has been updated. If the channel is
2674 // the default channel make sure that all the receive channels are updated as
2675 // well. Receive channels have to have the same SSRC as the default channel in
2676 // order to send receiver reports with this SSRC.
2677 if (IsDefaultChannel(channel)) {
2678 for (ChannelMap::const_iterator it = receive_channels_.begin();
2679 it != receive_channels_.end(); ++it) {
2680 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002681 if (!IsDefaultChannel(it->second->channel())) {
2682 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002683 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002684 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002685 return false;
2686 }
2687 }
2688 }
2689 }
2690
2691 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002692 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2693 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002694 }
2695
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002696 // Set the current codecs to be used for the new channel.
2697 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002698 return false;
2699
2700 return ChangeSend(channel, desired_send_);
2701}
2702
2703bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2704 ChannelMap::iterator it = send_channels_.find(ssrc);
2705 if (it == send_channels_.end()) {
2706 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2707 << " which doesn't exist.";
2708 return false;
2709 }
2710
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002711 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002712 ChangeSend(channel, SEND_NOTHING);
2713
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002714 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2715 // this will disconnect the audio renderer with the send channel.
2716 delete it->second;
2717 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002718
2719 if (IsDefaultChannel(channel)) {
2720 // Do not delete the default channel since the receive channels depend on
2721 // the default channel, recycle it instead.
2722 ChangeSend(channel, SEND_NOTHING);
2723 } else {
2724 // Clean up and delete the send channel.
2725 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2726 << " with VoiceEngine channel #" << channel << ".";
2727 if (!DeleteChannel(channel))
2728 return false;
2729 }
2730
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002731 if (send_channels_.empty())
2732 ChangeSend(SEND_NOTHING);
2733
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734 return true;
2735}
2736
2737bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002738 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002739 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740
2741 if (!VERIFY(sp.ssrcs.size() == 1))
2742 return false;
2743 uint32 ssrc = sp.first_ssrc();
2744
wu@webrtc.org78187522013-10-07 23:32:02 +00002745 if (ssrc == 0) {
2746 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2747 return false;
2748 }
2749
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2751 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752 return false;
2753 }
2754
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002755 TryAddAudioRecvStream(ssrc);
2756
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002757 // Reuse default channel for recv stream in non-conference mode call
2758 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002759 webrtc::AudioTransport* audio_transport =
2760 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002762 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2763 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002764 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002765 default_receive_ssrc_,
2766 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 return SetPlayout(voe_channel(), playout_);
2768 }
2769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002771 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 if (channel == -1) {
2773 LOG_RTCERR0(CreateChannel);
2774 return false;
2775 }
2776
wu@webrtc.org78187522013-10-07 23:32:02 +00002777 if (!ConfigureRecvChannel(channel)) {
2778 DeleteChannel(channel);
2779 return false;
2780 }
2781
2782 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002783 std::make_pair(
2784 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002785
2786 LOG(LS_INFO) << "New audio stream " << ssrc
2787 << " registered to VoiceEngine channel #"
2788 << channel << ".";
2789 return true;
2790}
2791
2792bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793 // Configure to use external transport, like our default channel.
2794 if (engine()->voe()->network()->RegisterExternalTransport(
2795 channel, *this) == -1) {
2796 LOG_RTCERR2(SetExternalTransport, channel, this);
2797 return false;
2798 }
2799
2800 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002801 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2803 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002804 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002805 return false;
2806 }
2807 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002808 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809 return false;
2810 }
2811
Minyue2013aec2015-05-13 14:14:42 +02002812 // Associate receive channel to default channel (so the receive channel can
2813 // obtain RTT from the send channel)
2814 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2815 LOG(LS_INFO) << "VoiceEngine channel #"
2816 << channel << " is associated with channel #"
2817 << voe_channel() << ".";
2818
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002819 // Use the same recv payload types as our default channel.
2820 ResetRecvCodecs(channel);
2821 if (!recv_codecs_.empty()) {
2822 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2823 it != recv_codecs_.end(); ++it) {
2824 webrtc::CodecInst voe_codec;
2825 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2826 voe_codec.pltype = it->id;
2827 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2828 if (engine()->voe()->codec()->GetRecPayloadType(
2829 voe_channel(), voe_codec) != -1) {
2830 if (engine()->voe()->codec()->SetRecPayloadType(
2831 channel, voe_codec) == -1) {
2832 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2833 return false;
2834 }
2835 }
2836 }
2837 }
2838 }
2839
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002840 if (InConferenceMode()) {
2841 // To be in par with the video, voe_channel() is not used for receiving in
2842 // a conference call.
2843 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2844 // This is the first stream in a multi user meeting. We can now
2845 // disable playback of the default stream. This since the default
2846 // stream will probably have received some initial packets before
2847 // the new stream was added. This will mean that the CN state from
2848 // the default channel will be mixed in with the other streams
2849 // throughout the whole meeting, which might be disturbing.
2850 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2851 SetPlayout(voe_channel(), false);
2852 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002854 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002856 // Set RTP header extension for the new channel.
2857 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2858 return false;
2859 }
2860
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002861 return SetPlayout(channel, playout_);
2862}
2863
2864bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002865 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002866 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002867 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002868 if (it == receive_channels_.end()) {
2869 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2870 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002871 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002872 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002874 TryRemoveAudioRecvStream(ssrc);
2875
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002876 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2877 // will disconnect the audio renderer with the receive channel.
2878 // Cache the channel before the deletion.
2879 const int channel = it->second->channel();
2880 delete it->second;
2881 receive_channels_.erase(it);
2882
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002883 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002884 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002885 // Recycle the default channel is for recv stream.
2886 if (playout_)
2887 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002888
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002889 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002890 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002892
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002893 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002894 << " with VoiceEngine channel #" << channel << ".";
2895 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002897
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002898 bool enable_default_channel_playout = false;
2899 if (receive_channels_.empty()) {
2900 // The last stream was removed. We can now enable the default
2901 // channel for new channels to be played out immediately without
2902 // waiting for AddStream messages.
2903 // We do this for both conference mode and non-conference mode.
2904 // TODO(oja): Does the default channel still have it's CN state?
2905 enable_default_channel_playout = true;
2906 }
2907 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2908 default_receive_ssrc_ != 0) {
2909 // Only the default channel is active, enable the playout on default
2910 // channel.
2911 enable_default_channel_playout = true;
2912 }
2913 if (enable_default_channel_playout && playout_) {
2914 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2915 SetPlayout(voe_channel(), true);
2916 }
2917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002918 return true;
2919}
2920
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002921bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2922 AudioRenderer* renderer) {
2923 ChannelMap::iterator it = receive_channels_.find(ssrc);
2924 if (it == receive_channels_.end()) {
2925 if (renderer) {
2926 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002927 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002928 return false;
2929 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002931 // The channel likely has gone away, do nothing.
2932 return true;
2933 }
2934
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002935 if (renderer)
2936 it->second->Start(renderer);
2937 else
2938 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002939
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002940 return true;
2941}
2942
2943bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2944 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002945 ChannelMap::iterator it = send_channels_.find(ssrc);
2946 if (it == send_channels_.end()) {
2947 if (renderer) {
2948 // Return an error if trying to set a valid renderer with an invalid ssrc.
2949 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2950 return false;
2951 }
2952
2953 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002954 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002955 }
2956
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002957 if (renderer)
2958 it->second->Start(renderer);
2959 else
2960 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002961
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002962 return true;
2963}
2964
2965bool WebRtcVoiceMediaChannel::GetActiveStreams(
2966 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002967 // In conference mode, the default channel should not be in
2968 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002970 for (ChannelMap::iterator it = receive_channels_.begin();
2971 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002972 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002973 if (level > 0) {
2974 actives->push_back(std::make_pair(it->first, level));
2975 }
2976 }
2977 return true;
2978}
2979
2980int WebRtcVoiceMediaChannel::GetOutputLevel() {
2981 // return the highest output level of all streams
2982 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002983 for (ChannelMap::iterator it = receive_channels_.begin();
2984 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002985 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002986 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987 }
2988 return highest;
2989}
2990
2991int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2992 int ret;
2993 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2994 // In case of error, log the info and continue
2995 LOG_RTCERR0(TimeSinceLastTyping);
2996 ret = -1;
2997 } else {
2998 ret *= 1000; // We return ms, webrtc returns seconds.
2999 }
3000 return ret;
3001}
3002
3003void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
3004 int cost_per_typing, int reporting_threshold, int penalty_decay,
3005 int type_event_delay) {
3006 if (engine()->voe()->processing()->SetTypingDetectionParameters(
3007 time_window, cost_per_typing,
3008 reporting_threshold, penalty_decay, type_event_delay) == -1) {
3009 // In case of error, log the info and continue
3010 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
3011 cost_per_typing, reporting_threshold, penalty_decay,
3012 type_event_delay);
3013 }
3014}
3015
3016bool WebRtcVoiceMediaChannel::SetOutputScaling(
3017 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003018 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 // Collect the channels to scale the output volume.
3020 std::vector<int> channels;
3021 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003022 // Default channel is not in receive_channels_ if it is not being used for
3023 // playout.
3024 if (default_receive_ssrc_ == 0)
3025 channels.push_back(voe_channel());
3026 for (ChannelMap::const_iterator it = receive_channels_.begin();
3027 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003028 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029 }
3030 } else { // Collect only the channel of the specified ssrc.
3031 int channel = GetReceiveChannelNum(ssrc);
3032 if (-1 == channel) {
3033 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3034 return false;
3035 }
3036 channels.push_back(channel);
3037 }
3038
3039 // Scale the output volume for the collected channels. We first normalize to
3040 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00003041 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003042 if (scale > 0.0001f) {
3043 left /= scale;
3044 right /= scale;
3045 }
3046 for (std::vector<int>::const_iterator it = channels.begin();
3047 it != channels.end(); ++it) {
3048 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
3049 *it, scale)) {
3050 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
3051 return false;
3052 }
3053 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
3054 *it, static_cast<float>(left), static_cast<float>(right))) {
3055 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
3056 // Do not return if fails. SetOutputVolumePan is not available for all
3057 // pltforms.
3058 }
3059 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
3060 << " right=" << right * scale
3061 << " for channel " << *it << " and ssrc " << ssrc;
3062 }
3063 return true;
3064}
3065
3066bool WebRtcVoiceMediaChannel::GetOutputScaling(
3067 uint32 ssrc, double* left, double* right) {
3068 if (!left || !right) return false;
3069
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003070 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003071 // Determine which channel based on ssrc.
3072 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3073 if (channel == -1) {
3074 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3075 return false;
3076 }
3077
3078 float scaling;
3079 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3080 channel, scaling)) {
3081 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3082 return false;
3083 }
3084
3085 float left_pan;
3086 float right_pan;
3087 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3088 channel, left_pan, right_pan)) {
3089 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3090 // If GetOutputVolumePan fails, we use the default left and right pan.
3091 left_pan = 1.0f;
3092 right_pan = 1.0f;
3093 }
3094
3095 *left = scaling * left_pan;
3096 *right = scaling * right_pan;
3097 return true;
3098}
3099
3100bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3101 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3102 return true;
3103}
3104
3105bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3106 bool play, bool loop) {
3107 if (!ringback_tone_) {
3108 return false;
3109 }
3110
3111 // The voe file api is not available in chrome.
3112 if (!engine()->voe()->file()) {
3113 return false;
3114 }
3115
3116 // Determine which VoiceEngine channel to play on.
3117 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3118 if (channel == -1) {
3119 return false;
3120 }
3121
3122 // Make sure the ringtone is cued properly, and play it out.
3123 if (play) {
3124 ringback_tone_->set_loop(loop);
3125 ringback_tone_->Rewind();
3126 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3127 ringback_tone_.get()) == -1) {
3128 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3129 LOG(LS_ERROR) << "Unable to start ringback tone";
3130 return false;
3131 }
3132 ringback_channels_.insert(channel);
3133 LOG(LS_INFO) << "Started ringback on channel " << channel;
3134 } else {
3135 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3136 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3137 LOG_RTCERR1(StopPlayingFileLocally, channel);
3138 return false;
3139 }
3140 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3141 ringback_channels_.erase(channel);
3142 }
3143
3144 return true;
3145}
3146
3147bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3148 return dtmf_allowed_;
3149}
3150
3151bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3152 int duration, int flags) {
3153 if (!dtmf_allowed_) {
3154 return false;
3155 }
3156
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157 // Send the event.
3158 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003159 int channel = -1;
3160 if (ssrc == 0) {
3161 bool default_channel_is_inuse = false;
3162 for (ChannelMap::const_iterator iter = send_channels_.begin();
3163 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003164 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003165 default_channel_is_inuse = true;
3166 break;
3167 }
3168 }
3169 if (default_channel_is_inuse) {
3170 channel = voe_channel();
3171 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003172 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003173 }
3174 } else {
3175 channel = GetSendChannelNum(ssrc);
3176 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003177 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3179 << ssrc << " is not in use.";
3180 return false;
3181 }
3182 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003183 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3184 channel, event, true, duration) == -1) {
3185 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 return false;
3187 }
3188 }
3189
3190 // Play the event.
3191 if (flags & cricket::DF_PLAY) {
3192 // Play DTMF tone locally.
3193 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3194 LOG_RTCERR2(PlayDtmfTone, event, duration);
3195 return false;
3196 }
3197 }
3198
3199 return true;
3200}
3201
wu@webrtc.orga9890802013-12-13 00:21:03 +00003202void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003203 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003204 DCHECK(thread_checker_.CalledOnValidThread());
3205
3206 // If hooked up to a "Call", forward packet there too.
3207 if (call_) {
3208 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3209 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3210 }
3211
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 // Pick which channel to send this packet to. If this packet doesn't match
3213 // any multiplexed streams, just send it to the default channel. Otherwise,
3214 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003215 int which_channel =
3216 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 if (which_channel == -1) {
3218 which_channel = voe_channel();
3219 }
3220
3221 // Stop any ringback that might be playing on the channel.
3222 // It's possible the ringback has already stopped, ih which case we'll just
3223 // use the opportunity to remove the channel from ringback_channels_.
3224 if (engine()->voe()->file()) {
3225 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3226 if (it != ringback_channels_.end()) {
3227 if (engine()->voe()->file()->IsPlayingFileLocally(
3228 which_channel) == 1) {
3229 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3230 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3231 << " due to incoming media";
3232 }
3233 ringback_channels_.erase(which_channel);
3234 }
3235 }
3236
3237 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003238 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003239 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003240 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003241}
3242
wu@webrtc.orga9890802013-12-13 00:21:03 +00003243void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003244 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003245 DCHECK(thread_checker_.CalledOnValidThread());
3246
3247 // If hooked up to a "Call", forward packet there too.
3248 if (call_) {
3249 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3250 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3251 }
3252
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003253 // Sending channels need all RTCP packets with feedback information.
3254 // Even sender reports can contain attached report blocks.
3255 // Receiving channels need sender reports in order to create
3256 // correct receiver reports.
3257 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003258 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003259 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3260 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 }
3262
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003263 // If it is a sender report, find the channel that is listening.
3264 bool has_sent_to_default_channel = false;
3265 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003266 int which_channel =
3267 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003268 if (which_channel != -1) {
3269 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003270 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003271
3272 if (IsDefaultChannel(which_channel))
3273 has_sent_to_default_channel = true;
3274 }
3275 }
3276
3277 // SR may continue RR and any RR entry may correspond to any one of the send
3278 // channels. So all RTCP packets must be forwarded all send channels. VoE
3279 // will filter out RR internally.
3280 for (ChannelMap::iterator iter = send_channels_.begin();
3281 iter != send_channels_.end(); ++iter) {
3282 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003283 if (IsDefaultChannel(iter->second->channel()) &&
3284 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003285 continue;
3286
3287 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003288 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003289 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290}
3291
3292bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003293 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3294 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3296 return false;
3297 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003298 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3299 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003300 return false;
3301 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003302 // We set the AGC to mute state only when all the channels are muted.
3303 // This implementation is not ideal, instead we should signal the AGC when
3304 // the mic channel is muted/unmuted. We can't do it today because there
3305 // is no good way to know which stream is mapping to the mic channel.
3306 bool all_muted = muted;
3307 for (ChannelMap::const_iterator iter = send_channels_.begin();
3308 iter != send_channels_.end() && all_muted; ++iter) {
3309 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3310 all_muted)) {
3311 LOG_RTCERR1(GetInputMute, iter->second->channel());
3312 return false;
3313 }
3314 }
3315
3316 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3317 if (ap)
3318 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 return true;
3320}
3321
minyue@webrtc.org26236952014-10-29 02:27:08 +00003322// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3323// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003324bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003325 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003326
minyue@webrtc.org26236952014-10-29 02:27:08 +00003327 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003328}
3329
minyue@webrtc.org26236952014-10-29 02:27:08 +00003330bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3331 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003332
minyue@webrtc.org26236952014-10-29 02:27:08 +00003333 send_bitrate_setting_ = true;
3334 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003335
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003337 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003338 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003339 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 }
3341
minyue@webrtc.org26236952014-10-29 02:27:08 +00003342 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003343 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3344 // SetMaxSendBandwith(0), the second call removes the previous limit.
3345 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 return true;
3347
3348 webrtc::CodecInst codec = *send_codec_;
3349 bool is_multi_rate = IsCodecMultiRate(codec);
3350
3351 if (is_multi_rate) {
3352 // If codec is multi-rate then just set the bitrate.
3353 codec.rate = bps;
3354 if (!SetSendCodec(codec)) {
3355 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3356 << " to bitrate " << bps << " bps.";
3357 return false;
3358 }
3359 return true;
3360 } else {
3361 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3362 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3363 // fixed bitrate then ignore.
3364 if (bps < codec.rate) {
3365 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3366 << " to bitrate " << bps << " bps"
3367 << ", requires at least " << codec.rate << " bps.";
3368 return false;
3369 }
3370 return true;
3371 }
3372}
3373
3374bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003375 bool echo_metrics_on = false;
3376 // These can take on valid negative values, so use the lowest possible level
3377 // as default rather than -1.
3378 int echo_return_loss = -100;
3379 int echo_return_loss_enhancement = -100;
3380 // These can also be negative, but in practice -1 is only used to signal
3381 // insufficient data, since the resolution is limited to multiples of 4 ms.
3382 int echo_delay_median_ms = -1;
3383 int echo_delay_std_ms = -1;
3384 if (engine()->voe()->processing()->GetEcMetricsStatus(
3385 echo_metrics_on) != -1 && echo_metrics_on) {
3386 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3387 // here, but it appears to be unsuitable currently. Revisit after this is
3388 // investigated: http://b/issue?id=5666755
3389 int erl, erle, rerl, anlp;
3390 if (engine()->voe()->processing()->GetEchoMetrics(
3391 erl, erle, rerl, anlp) != -1) {
3392 echo_return_loss = erl;
3393 echo_return_loss_enhancement = erle;
3394 }
3395
3396 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003397 float dummy;
3398 if (engine()->voe()->processing()->GetEcDelayMetrics(
3399 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003400 echo_delay_median_ms = median;
3401 echo_delay_std_ms = std;
3402 }
3403 }
3404
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003405 webrtc::CallStatistics cs;
3406 unsigned int ssrc;
3407 webrtc::CodecInst codec;
3408 unsigned int level;
3409
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003410 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3411 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003412 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003414 // Fill in the sender info, based on what we know, and what the
3415 // remote side told us it got from its RTCP report.
3416 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003418 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3419 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3420 continue;
3421 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003422
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003423 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003424 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3425 sinfo.bytes_sent = cs.bytesSent;
3426 sinfo.packets_sent = cs.packetsSent;
3427 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3428 // returns 0 to indicate an error value.
3429 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3430
3431 // Get data from the last remote RTCP report. Use default values if no data
3432 // available.
3433 sinfo.fraction_lost = -1.0;
3434 sinfo.jitter_ms = -1;
3435 sinfo.packets_lost = -1;
3436 sinfo.ext_seqnum = -1;
3437 std::vector<webrtc::ReportBlock> receive_blocks;
3438 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3439 channel, &receive_blocks) != -1 &&
3440 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3441 std::vector<webrtc::ReportBlock>::iterator iter;
3442 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3443 ++iter) {
3444 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003445 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003446 // Convert Q8 to floating point.
3447 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3448 // Convert samples to milliseconds.
3449 if (codec.plfreq / 1000 > 0) {
3450 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3451 }
3452 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3453 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3454 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003455 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456 }
3457 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003458
3459 // Local speech level.
3460 sinfo.audio_level = (engine()->voe()->volume()->
3461 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3462
3463 // TODO(xians): We are injecting the same APM logging to all the send
3464 // channels here because there is no good way to know which send channel
3465 // is using the APM. The correct fix is to allow the send channels to have
3466 // their own APM so that we can feed the correct APM logging to different
3467 // send channels. See issue crbug/264611 .
3468 sinfo.echo_return_loss = echo_return_loss;
3469 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3470 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3471 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003472 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3473 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003474 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003475
3476 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003477 }
3478
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003479 // Build the list of receivers, one for each receiving channel, or 1 in
3480 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003482 for (ChannelMap::const_iterator it = receive_channels_.begin();
3483 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003484 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 }
3486 if (channels.empty()) {
3487 channels.push_back(voe_channel());
3488 }
3489
3490 // Get the SSRC and stats for each receiver, based on our own calculations.
3491 for (std::vector<int>::const_iterator it = channels.begin();
3492 it != channels.end(); ++it) {
3493 memset(&cs, 0, sizeof(cs));
3494 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3495 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3496 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3497 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003498 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003499 rinfo.bytes_rcvd = cs.bytesReceived;
3500 rinfo.packets_rcvd = cs.packetsReceived;
3501 // The next four fields are from the most recently sent RTCP report.
3502 // Convert Q8 to floating point.
3503 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3504 rinfo.packets_lost = cs.cumulativeLost;
3505 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003506 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003507 if (codec.pltype != -1) {
3508 rinfo.codec_name = codec.plname;
3509 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510 // Convert samples to milliseconds.
3511 if (codec.plfreq / 1000 > 0) {
3512 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3513 }
3514
3515 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3516 webrtc::NetworkStatistics ns;
3517 if (engine()->voe()->neteq() &&
3518 engine()->voe()->neteq()->GetNetworkStatistics(
3519 *it, ns) != -1) {
3520 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3521 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3522 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003523 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003524 rinfo.speech_expand_rate =
3525 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3526 rinfo.secondary_decoded_rate =
3527 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003529
3530 webrtc::AudioDecodingCallStats ds;
3531 if (engine()->voe()->neteq() &&
3532 engine()->voe()->neteq()->GetDecodingCallStatistics(
3533 *it, &ds) != -1) {
3534 rinfo.decoding_calls_to_silence_generator =
3535 ds.calls_to_silence_generator;
3536 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3537 rinfo.decoding_normal = ds.decoded_normal;
3538 rinfo.decoding_plc = ds.decoded_plc;
3539 rinfo.decoding_cng = ds.decoded_cng;
3540 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3541 }
3542
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003543 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003544 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003545 int playout_buffer_delay_ms = 0;
3546 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003547 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3548 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3549 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003550 }
3551
3552 // Get speech level.
3553 rinfo.audio_level = (engine()->voe()->volume()->
3554 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3555 info->receivers.push_back(rinfo);
3556 }
3557 }
3558
3559 return true;
3560}
3561
3562void WebRtcVoiceMediaChannel::GetLastMediaError(
3563 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003564 DCHECK(ssrc != NULL);
3565 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003566 FindSsrc(voe_channel(), ssrc);
3567 *error = WebRtcErrorToChannelError(GetLastEngineError());
3568}
3569
3570bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003571 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003572 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003573 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003574 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3575 // This means the error is not limited to a specific channel. Signal the
3576 // message using ssrc=0. If the current channel is sending, use this
3577 // channel for sending the message.
3578 *ssrc = 0;
3579 return true;
3580 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003581 // Check whether this is a sending channel.
3582 for (ChannelMap::const_iterator it = send_channels_.begin();
3583 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003584 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003585 // This is a sending channel.
3586 uint32 local_ssrc = 0;
3587 if (engine()->voe()->rtp()->GetLocalSSRC(
3588 channel_num, local_ssrc) != -1) {
3589 *ssrc = local_ssrc;
3590 }
3591 return true;
3592 }
3593 }
3594
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003595 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003596 for (ChannelMap::const_iterator it = receive_channels_.begin();
3597 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003598 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003599 *ssrc = it->first;
3600 return true;
3601 }
3602 }
3603 }
3604 return false;
3605}
3606
3607void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003608 if (error == VE_TYPING_NOISE_WARNING) {
3609 typing_noise_detected_ = true;
3610 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3611 typing_noise_detected_ = false;
3612 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003613 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3614}
3615
3616int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3617 unsigned int ulevel;
3618 int ret =
3619 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3620 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3621}
3622
3623int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003624 ChannelMap::iterator it = receive_channels_.find(ssrc);
3625 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003626 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003627 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3628}
3629
3630int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003631 ChannelMap::iterator it = send_channels_.find(ssrc);
3632 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003633 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003634
3635 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003636}
3637
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003638void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3639 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003640 for (const auto& it : receive_channels_) {
3641 TryRemoveAudioRecvStream(it.first);
3642 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003643 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003644 for (const auto& it : receive_channels_) {
3645 TryAddAudioRecvStream(it.first);
3646 }
3647}
3648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003649bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3650 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3651 // Get the RED encodings from the parameter with no name. This may
3652 // change based on what is discussed on the Jingle list.
3653 // The encoding parameter is of the form "a/b"; we only support where
3654 // a == b. Verify this and parse out the value into red_pt.
3655 // If the parameter value is absent (as it will be until we wire up the
3656 // signaling of this message), use the second codec specified (i.e. the
3657 // one after "red") as the encoding parameter.
3658 int red_pt = -1;
3659 std::string red_params;
3660 CodecParameterMap::const_iterator it = red_codec.params.find("");
3661 if (it != red_codec.params.end()) {
3662 red_params = it->second;
3663 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003664 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003665 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003666 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003667 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3668 return false;
3669 }
3670 } else if (red_codec.params.empty()) {
3671 LOG(LS_WARNING) << "RED params not present, using defaults";
3672 if (all_codecs.size() > 1) {
3673 red_pt = all_codecs[1].id;
3674 }
3675 }
3676
3677 // Try to find red_pt in |codecs|.
3678 std::vector<AudioCodec>::const_iterator codec;
3679 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3680 if (codec->id == red_pt)
3681 break;
3682 }
3683
3684 // If we find the right codec, that will be the codec we pass to
3685 // SetSendCodec, with the desired payload type.
3686 if (codec != all_codecs.end() &&
3687 engine()->FindWebRtcCodec(*codec, send_codec)) {
3688 } else {
3689 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3690 return false;
3691 }
3692
3693 return true;
3694}
3695
3696bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3697 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003698 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699 return false;
3700 }
3701 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3702 // what we want to do with them.
3703 // engine()->voe().EnableVQMon(voe_channel(), true);
3704 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3705 return true;
3706}
3707
3708bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3709 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3710 for (int i = 0; i < ncodecs; ++i) {
3711 webrtc::CodecInst voe_codec;
3712 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3713 voe_codec.pltype = -1;
3714 if (engine()->voe()->codec()->SetRecPayloadType(
3715 channel, voe_codec) == -1) {
3716 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3717 return false;
3718 }
3719 }
3720 }
3721 return true;
3722}
3723
3724bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3725 if (playout) {
3726 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3727 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3728 LOG_RTCERR1(StartPlayout, channel);
3729 return false;
3730 }
3731 } else {
3732 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3733 engine()->voe()->base()->StopPlayout(channel);
3734 }
3735 return true;
3736}
3737
3738uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3739 bool rtcp) {
3740 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3741 uint32 ssrc = 0;
3742 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003743 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003744 }
3745 return ssrc;
3746}
3747
3748// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3749VoiceMediaChannel::Error
3750 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3751 switch (err_code) {
3752 case 0:
3753 return ERROR_NONE;
3754 case VE_CANNOT_START_RECORDING:
3755 case VE_MIC_VOL_ERROR:
3756 case VE_GET_MIC_VOL_ERROR:
3757 case VE_CANNOT_ACCESS_MIC_VOL:
3758 return ERROR_REC_DEVICE_OPEN_FAILED;
3759 case VE_SATURATION_WARNING:
3760 return ERROR_REC_DEVICE_SATURATION;
3761 case VE_REC_DEVICE_REMOVED:
3762 return ERROR_REC_DEVICE_REMOVED;
3763 case VE_RUNTIME_REC_WARNING:
3764 case VE_RUNTIME_REC_ERROR:
3765 return ERROR_REC_RUNTIME_ERROR;
3766 case VE_CANNOT_START_PLAYOUT:
3767 case VE_SPEAKER_VOL_ERROR:
3768 case VE_GET_SPEAKER_VOL_ERROR:
3769 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3770 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3771 case VE_RUNTIME_PLAY_WARNING:
3772 case VE_RUNTIME_PLAY_ERROR:
3773 return ERROR_PLAY_RUNTIME_ERROR;
3774 case VE_TYPING_NOISE_WARNING:
3775 return ERROR_REC_TYPING_NOISE_DETECTED;
3776 default:
3777 return VoiceMediaChannel::ERROR_OTHER;
3778 }
3779}
3780
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003781bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3782 int channel_id, const RtpHeaderExtension* extension) {
3783 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003784 int id = 0;
3785 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003786 if (extension) {
3787 enable = true;
3788 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003789 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003790 }
3791 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003792 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003793 return false;
3794 }
3795 return true;
3796}
3797
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003798void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3799 DCHECK(thread_checker_.CalledOnValidThread());
3800 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3801 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3802 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3803 webrtc::AudioReceiveStream::Config config;
3804 config.rtp.remote_ssrc = ssrc;
3805 config.rtp.extensions = recv_rtp_extensions_;
3806 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3807 receive_streams_.insert(std::make_pair(ssrc, s));
3808 }
3809}
3810
3811void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3812 DCHECK(thread_checker_.CalledOnValidThread());
3813 // If we are hooked up to a webrtc::Call, assume there is an
3814 // AudioReceiveStream to destroy too.
3815 if (call_) {
3816 auto stream_it = receive_streams_.find(ssrc);
3817 if (stream_it != receive_streams_.end()) {
3818 call_->DestroyAudioReceiveStream(stream_it->second);
3819 receive_streams_.erase(stream_it);
3820 }
3821 }
3822}
3823
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003824int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003825 size_t res = 0;
3826 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003827 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003828}
3829
3830int WebRtcSoundclipStream::Rewind() {
3831 mem_.Rewind();
3832 // Return -1 to keep VoiceEngine from looping.
3833 return (loop_) ? 0 : -1;
3834}
3835
3836} // namespace cricket
3837
3838#endif // HAVE_WEBRTC_VOICE