blob: 39066720cb3201bd098d5686b7c2c20c7ab7e0f2 [file] [log] [blame]
solenbergc7a8b082015-10-16 14:35:07 -07001/*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/audio/audio_send_stream.h"
12
13#include <string>
14
solenberg566ef242015-11-06 15:34:49 -080015#include "webrtc/audio/audio_state.h"
solenberg85a04962015-10-27 03:35:21 -070016#include "webrtc/audio/conversion.h"
solenberg566ef242015-11-06 15:34:49 -080017#include "webrtc/audio/scoped_voe_interface.h"
solenbergc7a8b082015-10-16 14:35:07 -070018#include "webrtc/base/checks.h"
perkj26091b12016-09-01 01:17:40 -070019#include "webrtc/base/event.h"
solenbergc7a8b082015-10-16 14:35:07 -070020#include "webrtc/base/logging.h"
perkj26091b12016-09-01 01:17:40 -070021#include "webrtc/base/task_queue.h"
Stefan Holmer80e12072016-02-23 13:30:42 +010022#include "webrtc/modules/congestion_controller/include/congestion_controller.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010023#include "webrtc/modules/pacing/paced_sender.h"
24#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h"
solenberg13725082015-11-25 08:16:52 -080025#include "webrtc/voice_engine/channel_proxy.h"
solenberg85a04962015-10-27 03:35:21 -070026#include "webrtc/voice_engine/include/voe_audio_processing.h"
27#include "webrtc/voice_engine/include/voe_codec.h"
28#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
29#include "webrtc/voice_engine/include/voe_volume_control.h"
solenberg13725082015-11-25 08:16:52 -080030#include "webrtc/voice_engine/voice_engine_impl.h"
solenbergc7a8b082015-10-16 14:35:07 -070031
32namespace webrtc {
minyue7a973442016-10-20 03:27:12 -070033
34namespace {
35
36constexpr char kOpusCodecName[] = "opus";
37
minyue7a973442016-10-20 03:27:12 -070038bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
39 return (_stricmp(codec.plname, ref_name) == 0);
40}
minyue7a973442016-10-20 03:27:12 -070041} // namespace
42
solenbergc7a8b082015-10-16 14:35:07 -070043namespace internal {
solenberg566ef242015-11-06 15:34:49 -080044AudioSendStream::AudioSendStream(
45 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +010046 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -070047 rtc::TaskQueue* worker_queue,
mflodman86cc6ff2016-07-26 04:44:06 -070048 CongestionController* congestion_controller,
tereliuse035e2d2016-09-21 06:51:47 -070049 BitrateAllocator* bitrate_allocator,
sprang982bf892016-10-13 06:23:11 -070050 RtcEventLog* event_log)
perkj26091b12016-09-01 01:17:40 -070051 : worker_queue_(worker_queue),
52 config_(config),
mflodman86cc6ff2016-07-26 04:44:06 -070053 audio_state_(audio_state),
54 bitrate_allocator_(bitrate_allocator) {
solenbergc7a8b082015-10-16 14:35:07 -070055 LOG(LS_INFO) << "AudioSendStream: " << config_.ToString();
solenberg566ef242015-11-06 15:34:49 -080056 RTC_DCHECK_NE(config_.voe_channel_id, -1);
57 RTC_DCHECK(audio_state_.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +010058 RTC_DCHECK(congestion_controller);
solenberg3a941542015-11-16 07:34:50 -080059
solenberg13725082015-11-25 08:16:52 -080060 VoiceEngineImpl* voe_impl = static_cast<VoiceEngineImpl*>(voice_engine());
kwibergfffa42b2016-02-23 10:46:32 -080061 channel_proxy_ = voe_impl->GetChannelProxy(config_.voe_channel_id);
tereliuse035e2d2016-09-21 06:51:47 -070062 channel_proxy_->SetRtcEventLog(event_log);
stefanbba9dec2016-02-01 04:39:55 -080063 channel_proxy_->RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +010064 congestion_controller->pacer(),
65 congestion_controller->GetTransportFeedbackObserver(),
66 congestion_controller->packet_router());
solenberg13725082015-11-25 08:16:52 -080067 channel_proxy_->SetRTCPStatus(true);
68 channel_proxy_->SetLocalSSRC(config.rtp.ssrc);
69 channel_proxy_->SetRTCP_CNAME(config.rtp.c_name);
solenberg971cab02016-06-14 10:02:41 -070070 // TODO(solenberg): Config NACK history window (which is a packet count),
71 // using the actual packet size for the configured codec.
72 channel_proxy_->SetNACKStatus(config_.rtp.nack.rtp_history_ms != 0,
73 config_.rtp.nack.rtp_history_ms / 20);
Stefan Holmerb86d4e42015-12-07 10:26:18 +010074
mflodman3d7db262016-04-29 00:57:13 -070075 channel_proxy_->RegisterExternalTransport(config.send_transport);
76
solenberg3a941542015-11-16 07:34:50 -080077 for (const auto& extension : config.rtp.extensions) {
stefanb521aa72016-11-01 03:17:16 -070078 if (extension.uri == RtpExtension::kAudioLevelUri) {
solenberg358057b2015-11-27 10:46:42 -080079 channel_proxy_->SetSendAudioLevelIndicationStatus(true, extension.id);
isheriff6f8d6862016-05-26 11:24:55 -070080 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
Stefan Holmerb86d4e42015-12-07 10:26:18 +010081 channel_proxy_->EnableSendTransportSequenceNumber(extension.id);
solenberg3a941542015-11-16 07:34:50 -080082 } else {
83 RTC_NOTREACHED() << "Registering unsupported RTP extension.";
84 }
85 }
minyue7a973442016-10-20 03:27:12 -070086 if (!SetupSendCodec()) {
87 LOG(LS_ERROR) << "Failed to set up send codec state.";
88 }
solenbergc7a8b082015-10-16 14:35:07 -070089}
90
91AudioSendStream::~AudioSendStream() {
solenberg85a04962015-10-27 03:35:21 -070092 RTC_DCHECK(thread_checker_.CalledOnValidThread());
solenbergc7a8b082015-10-16 14:35:07 -070093 LOG(LS_INFO) << "~AudioSendStream: " << config_.ToString();
mflodman3d7db262016-04-29 00:57:13 -070094 channel_proxy_->DeRegisterExternalTransport();
stefanbba9dec2016-02-01 04:39:55 -080095 channel_proxy_->ResetCongestionControlObjects();
tereliuse035e2d2016-09-21 06:51:47 -070096 channel_proxy_->SetRtcEventLog(nullptr);
solenbergc7a8b082015-10-16 14:35:07 -070097}
98
solenberg3a941542015-11-16 07:34:50 -080099void AudioSendStream::Start() {
100 RTC_DCHECK(thread_checker_.CalledOnValidThread());
mflodman86cc6ff2016-07-26 04:44:06 -0700101 if (config_.min_bitrate_kbps != -1 && config_.max_bitrate_kbps != -1) {
102 RTC_DCHECK_GE(config_.max_bitrate_kbps, config_.min_bitrate_kbps);
perkj26091b12016-09-01 01:17:40 -0700103 rtc::Event thread_sync_event(false /* manual_reset */, false);
104 worker_queue_->PostTask([this, &thread_sync_event] {
105 bitrate_allocator_->AddObserver(this, config_.min_bitrate_kbps * 1000,
106 config_.max_bitrate_kbps * 1000, 0, true);
107 thread_sync_event.Set();
108 });
109 thread_sync_event.Wait(rtc::Event::kForever);
mflodman86cc6ff2016-07-26 04:44:06 -0700110 }
111
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -0800112 ScopedVoEInterface<VoEBase> base(voice_engine());
113 int error = base->StartSend(config_.voe_channel_id);
114 if (error != 0) {
115 LOG(LS_ERROR) << "AudioSendStream::Start failed with error: " << error;
116 }
solenberg3a941542015-11-16 07:34:50 -0800117}
118
119void AudioSendStream::Stop() {
120 RTC_DCHECK(thread_checker_.CalledOnValidThread());
perkj26091b12016-09-01 01:17:40 -0700121 rtc::Event thread_sync_event(false /* manual_reset */, false);
122 worker_queue_->PostTask([this, &thread_sync_event] {
123 bitrate_allocator_->RemoveObserver(this);
124 thread_sync_event.Set();
125 });
126 thread_sync_event.Wait(rtc::Event::kForever);
127
Taylor Brandstetter1a018dc2016-03-08 12:37:39 -0800128 ScopedVoEInterface<VoEBase> base(voice_engine());
129 int error = base->StopSend(config_.voe_channel_id);
130 if (error != 0) {
131 LOG(LS_ERROR) << "AudioSendStream::Stop failed with error: " << error;
132 }
solenberg3a941542015-11-16 07:34:50 -0800133}
134
solenberg8842c3e2016-03-11 03:06:41 -0800135bool AudioSendStream::SendTelephoneEvent(int payload_type, int event,
136 int duration_ms) {
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100137 RTC_DCHECK(thread_checker_.CalledOnValidThread());
138 return channel_proxy_->SetSendTelephoneEventPayloadType(payload_type) &&
139 channel_proxy_->SendTelephoneEventOutband(event, duration_ms);
140}
141
solenberg94218532016-06-16 10:53:22 -0700142void AudioSendStream::SetMuted(bool muted) {
143 RTC_DCHECK(thread_checker_.CalledOnValidThread());
144 channel_proxy_->SetInputMute(muted);
145}
146
solenbergc7a8b082015-10-16 14:35:07 -0700147webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
solenberg85a04962015-10-27 03:35:21 -0700148 RTC_DCHECK(thread_checker_.CalledOnValidThread());
149 webrtc::AudioSendStream::Stats stats;
150 stats.local_ssrc = config_.rtp.ssrc;
solenberg3a941542015-11-16 07:34:50 -0800151 ScopedVoEInterface<VoEAudioProcessing> processing(voice_engine());
152 ScopedVoEInterface<VoECodec> codec(voice_engine());
solenberg3a941542015-11-16 07:34:50 -0800153 ScopedVoEInterface<VoEVolumeControl> volume(voice_engine());
solenberg85a04962015-10-27 03:35:21 -0700154
solenberg358057b2015-11-27 10:46:42 -0800155 webrtc::CallStatistics call_stats = channel_proxy_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700156 stats.bytes_sent = call_stats.bytesSent;
157 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800158 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
159 // returns 0 to indicate an error value.
160 if (call_stats.rttMs > 0) {
161 stats.rtt_ms = call_stats.rttMs;
162 }
163 // TODO(solenberg): [was ajm]: Re-enable this metric once we have a reliable
164 // implementation.
165 stats.aec_quality_min = -1;
solenberg85a04962015-10-27 03:35:21 -0700166
167 webrtc::CodecInst codec_inst = {0};
168 if (codec->GetSendCodec(config_.voe_channel_id, codec_inst) != -1) {
169 RTC_DCHECK_NE(codec_inst.pltype, -1);
170 stats.codec_name = codec_inst.plname;
171
172 // Get data from the last remote RTCP report.
solenberg358057b2015-11-27 10:46:42 -0800173 for (const auto& block : channel_proxy_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800174 // Lookup report for send ssrc only.
175 if (block.source_SSRC == stats.local_ssrc) {
176 stats.packets_lost = block.cumulative_num_packets_lost;
177 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
178 stats.ext_seqnum = block.extended_highest_sequence_number;
179 // Convert samples to milliseconds.
180 if (codec_inst.plfreq / 1000 > 0) {
181 stats.jitter_ms =
182 block.interarrival_jitter / (codec_inst.plfreq / 1000);
solenberg85a04962015-10-27 03:35:21 -0700183 }
solenberg8b85de22015-11-16 09:48:04 -0800184 break;
solenberg85a04962015-10-27 03:35:21 -0700185 }
186 }
187 }
188
solenberg85a04962015-10-27 03:35:21 -0700189 // Local speech level.
190 {
191 unsigned int level = 0;
solenberg358057b2015-11-27 10:46:42 -0800192 int error = volume->GetSpeechInputLevelFullRange(level);
solenberg8b85de22015-11-16 09:48:04 -0800193 RTC_DCHECK_EQ(0, error);
194 stats.audio_level = static_cast<int32_t>(level);
solenberg85a04962015-10-27 03:35:21 -0700195 }
196
solenberg85a04962015-10-27 03:35:21 -0700197 bool echo_metrics_on = false;
solenberg358057b2015-11-27 10:46:42 -0800198 int error = processing->GetEcMetricsStatus(echo_metrics_on);
solenberg8b85de22015-11-16 09:48:04 -0800199 RTC_DCHECK_EQ(0, error);
200 if (echo_metrics_on) {
solenberg85a04962015-10-27 03:35:21 -0700201 // These can also be negative, but in practice -1 is only used to signal
202 // insufficient data, since the resolution is limited to multiples of 4 ms.
203 int median = -1;
204 int std = -1;
205 float dummy = 0.0f;
solenberg8b85de22015-11-16 09:48:04 -0800206 error = processing->GetEcDelayMetrics(median, std, dummy);
207 RTC_DCHECK_EQ(0, error);
208 stats.echo_delay_median_ms = median;
209 stats.echo_delay_std_ms = std;
solenberg85a04962015-10-27 03:35:21 -0700210
211 // These can take on valid negative values, so use the lowest possible level
212 // as default rather than -1.
213 int erl = -100;
214 int erle = -100;
215 int dummy1 = 0;
216 int dummy2 = 0;
solenberg8b85de22015-11-16 09:48:04 -0800217 error = processing->GetEchoMetrics(erl, erle, dummy1, dummy2);
218 RTC_DCHECK_EQ(0, error);
219 stats.echo_return_loss = erl;
220 stats.echo_return_loss_enhancement = erle;
solenberg85a04962015-10-27 03:35:21 -0700221 }
222
ivoc8c63a822016-10-21 04:10:03 -0700223 // TODO(ivoc): Hook this up to the residual echo detector.
224 stats.residual_echo_likelihood = 0.0f;
225
solenberg3a941542015-11-16 07:34:50 -0800226 internal::AudioState* audio_state =
227 static_cast<internal::AudioState*>(audio_state_.get());
solenberg566ef242015-11-06 15:34:49 -0800228 stats.typing_noise_detected = audio_state->typing_noise_detected();
solenberg85a04962015-10-27 03:35:21 -0700229
230 return stats;
231}
232
pbos1ba8d392016-05-01 20:18:34 -0700233void AudioSendStream::SignalNetworkState(NetworkState state) {
234 RTC_DCHECK(thread_checker_.CalledOnValidThread());
235}
236
237bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
238 // TODO(solenberg): Tests call this function on a network thread, libjingle
239 // calls on the worker thread. We should move towards always using a network
240 // thread. Then this check can be enabled.
241 // RTC_DCHECK(!thread_checker_.CalledOnValidThread());
242 return channel_proxy_->ReceivedRTCPPacket(packet, length);
243}
244
mflodman86cc6ff2016-07-26 04:44:06 -0700245uint32_t AudioSendStream::OnBitrateUpdated(uint32_t bitrate_bps,
246 uint8_t fraction_loss,
247 int64_t rtt) {
248 RTC_DCHECK_GE(bitrate_bps,
249 static_cast<uint32_t>(config_.min_bitrate_kbps * 1000));
250 // The bitrate allocator might allocate an higher than max configured bitrate
251 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
252 const uint32_t max_bitrate_bps = config_.max_bitrate_kbps * 1000;
253 if (bitrate_bps > max_bitrate_bps)
254 bitrate_bps = max_bitrate_bps;
255
256 channel_proxy_->SetBitrate(bitrate_bps);
257
258 // The amount of audio protection is not exposed by the encoder, hence
259 // always returning 0.
260 return 0;
261}
262
solenberg85a04962015-10-27 03:35:21 -0700263const webrtc::AudioSendStream::Config& AudioSendStream::config() const {
264 RTC_DCHECK(thread_checker_.CalledOnValidThread());
265 return config_;
solenbergc7a8b082015-10-16 14:35:07 -0700266}
267
solenberg3a941542015-11-16 07:34:50 -0800268VoiceEngine* AudioSendStream::voice_engine() const {
269 internal::AudioState* audio_state =
270 static_cast<internal::AudioState*>(audio_state_.get());
271 VoiceEngine* voice_engine = audio_state->voice_engine();
272 RTC_DCHECK(voice_engine);
273 return voice_engine;
solenbergc7a8b082015-10-16 14:35:07 -0700274}
minyue7a973442016-10-20 03:27:12 -0700275
276// Apply current codec settings to a single voe::Channel used for sending.
277bool AudioSendStream::SetupSendCodec() {
278 ScopedVoEInterface<VoEBase> base(voice_engine());
279 ScopedVoEInterface<VoECodec> codec(voice_engine());
280
281 const int channel = config_.voe_channel_id;
282
283 // Disable VAD and FEC unless we know the other side wants them.
284 codec->SetVADStatus(channel, false);
285 codec->SetFECStatus(channel, false);
286
287 const auto& send_codec_spec = config_.send_codec_spec;
288
solenberg940b6d62016-10-25 11:19:07 -0700289 // We set the codec first, since the below extra configuration is only applied
290 // to the "current" codec.
minyue7a973442016-10-20 03:27:12 -0700291
292 // If codec is already configured, we do not it again.
293 // TODO(minyue): check if this check is really needed, or can we move it into
294 // |codec->SetSendCodec|.
295 webrtc::CodecInst current_codec = {0};
296 if (codec->GetSendCodec(channel, current_codec) != 0 ||
297 (send_codec_spec.codec_inst != current_codec)) {
298 if (codec->SetSendCodec(channel, send_codec_spec.codec_inst) == -1) {
solenberg940b6d62016-10-25 11:19:07 -0700299 LOG(LS_WARNING) << "SetSendCodec() failed: " << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700300 return false;
301 }
302 }
303
solenberg940b6d62016-10-25 11:19:07 -0700304 // Codec internal FEC. Treat any failure as fatal internal error.
minyue7a973442016-10-20 03:27:12 -0700305 if (send_codec_spec.enable_codec_fec) {
solenberg940b6d62016-10-25 11:19:07 -0700306 if (codec->SetFECStatus(channel, true) != 0) {
307 LOG(LS_WARNING) << "SetFECStatus() failed: " << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700308 return false;
309 }
310 }
311
solenberg940b6d62016-10-25 11:19:07 -0700312 // DTX and maxplaybackrate are only set if current codec is Opus.
minyue7a973442016-10-20 03:27:12 -0700313 if (IsCodec(send_codec_spec.codec_inst, kOpusCodecName)) {
solenberg940b6d62016-10-25 11:19:07 -0700314 if (codec->SetOpusDtx(channel, send_codec_spec.enable_opus_dtx) != 0) {
315 LOG(LS_WARNING) << "SetOpusDtx() failed: " << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700316 return false;
317 }
318
319 // If opus_max_playback_rate <= 0, the default maximum playback rate
320 // (48 kHz) will be used.
321 if (send_codec_spec.opus_max_playback_rate > 0) {
minyue7a973442016-10-20 03:27:12 -0700322 if (codec->SetOpusMaxPlaybackRate(
solenberg940b6d62016-10-25 11:19:07 -0700323 channel, send_codec_spec.opus_max_playback_rate) != 0) {
324 LOG(LS_WARNING) << "SetOpusMaxPlaybackRate() failed: "
325 << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700326 return false;
327 }
328 }
minyue6b825df2016-10-31 04:08:32 -0700329
330 if (config_.audio_network_adaptor_config) {
331 // Audio network adaptor is only allowed for Opus currently.
332 // |SetReceiverFrameLengthRange| needs to be called before
333 // |EnableAudioNetworkAdaptor|.
334 channel_proxy_->SetReceiverFrameLengthRange(send_codec_spec.min_ptime_ms,
335 send_codec_spec.max_ptime_ms);
336 channel_proxy_->EnableAudioNetworkAdaptor(
337 *config_.audio_network_adaptor_config);
338 LOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
339 << config_.rtp.ssrc;
340 } else {
341 channel_proxy_->DisableAudioNetworkAdaptor();
342 }
minyue7a973442016-10-20 03:27:12 -0700343 }
344
345 // Set the CN payloadtype and the VAD status.
346 if (send_codec_spec.cng_payload_type != -1) {
347 // The CN payload type for 8000 Hz clockrate is fixed at 13.
348 if (send_codec_spec.cng_plfreq != 8000) {
349 webrtc::PayloadFrequencies cn_freq;
350 switch (send_codec_spec.cng_plfreq) {
351 case 16000:
352 cn_freq = webrtc::kFreq16000Hz;
353 break;
354 case 32000:
355 cn_freq = webrtc::kFreq32000Hz;
356 break;
357 default:
358 RTC_NOTREACHED();
359 return false;
360 }
361 if (codec->SetSendCNPayloadType(channel, send_codec_spec.cng_payload_type,
solenberg940b6d62016-10-25 11:19:07 -0700362 cn_freq) != 0) {
363 LOG(LS_WARNING) << "SetSendCNPayloadType() failed: "
364 << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700365 // TODO(ajm): This failure condition will be removed from VoE.
366 // Restore the return here when we update to a new enough webrtc.
367 //
368 // Not returning false because the SetSendCNPayloadType will fail if
369 // the channel is already sending.
370 // This can happen if the remote description is applied twice, for
371 // example in the case of ROAP on top of JSEP, where both side will
372 // send the offer.
373 }
374 }
375
376 // Only turn on VAD if we have a CN payload type that matches the
377 // clockrate for the codec we are going to use.
378 if (send_codec_spec.cng_plfreq == send_codec_spec.codec_inst.plfreq &&
379 send_codec_spec.codec_inst.channels == 1) {
380 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
381 // interaction between VAD and Opus FEC.
solenberg940b6d62016-10-25 11:19:07 -0700382 if (codec->SetVADStatus(channel, true) != 0) {
383 LOG(LS_WARNING) << "SetVADStatus() failed: " << base->LastError();
minyue7a973442016-10-20 03:27:12 -0700384 return false;
385 }
386 }
387 }
388 return true;
389}
390
solenbergc7a8b082015-10-16 14:35:07 -0700391} // namespace internal
392} // namespace webrtc