blob: 8ff34ed55a1f16345a10509bb8e3e3406c7c12c2 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "audio/audio_send_stream.h"
solenbergc7a8b082015-10-16 14:35:07 -070012
13#include <string>
ossu20a4b3f2017-04-27 02:08:52 -070014#include <utility>
15#include <vector>
solenbergc7a8b082015-10-16 14:35:07 -070016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "audio/audio_state.h"
Fredrik Solenberga8b7c7f2018-01-17 11:18:31 +010018#include "audio/channel_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "audio/conversion.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "call/rtp_transport_controller_send_interface.h"
21#include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/checks.h"
23#include "rtc_base/event.h"
24#include "rtc_base/function_view.h"
25#include "rtc_base/logging.h"
26#include "rtc_base/task_queue.h"
27#include "rtc_base/timeutils.h"
Alex Narestcedd3512017-12-07 20:54:55 +010028#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070029
30namespace webrtc {
solenbergc7a8b082015-10-16 14:35:07 -070031namespace internal {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010032namespace {
eladalonedd6eea2017-05-25 00:15:35 -070033// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070034constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
35constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
36constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
37
ossu20a4b3f2017-04-27 02:08:52 -070038void CallEncoder(const std::unique_ptr<voe::ChannelProxy>& channel_proxy,
39 rtc::FunctionView<void(AudioEncoder*)> lambda) {
40 channel_proxy->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
41 RTC_DCHECK(encoder_ptr);
42 lambda(encoder_ptr->get());
43 });
44}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010045
46std::unique_ptr<voe::ChannelProxy> CreateChannelAndProxy(
47 webrtc::AudioState* audio_state,
48 rtc::TaskQueue* worker_queue,
49 ProcessThread* module_process_thread) {
50 RTC_DCHECK(audio_state);
51 internal::AudioState* internal_audio_state =
52 static_cast<internal::AudioState*>(audio_state);
53 return std::unique_ptr<voe::ChannelProxy>(new voe::ChannelProxy(
54 std::unique_ptr<voe::Channel>(new voe::Channel(
55 worker_queue,
56 module_process_thread,
57 internal_audio_state->audio_device_module()))));
58}
ossu20a4b3f2017-04-27 02:08:52 -070059} // namespace
60
Sam Zackrisson06953ba2018-02-01 16:53:16 +010061// Helper class to track the actively sending lifetime of this stream.
sazac58f8c02017-07-19 00:39:19 -070062class AudioSendStream::TimedTransport : public Transport {
63 public:
64 TimedTransport(Transport* transport, TimeInterval* time_interval)
65 : transport_(transport), lifetime_(time_interval) {}
66 bool SendRtp(const uint8_t* packet,
67 size_t length,
68 const PacketOptions& options) {
69 if (lifetime_) {
70 lifetime_->Extend();
71 }
72 return transport_->SendRtp(packet, length, options);
73 }
74 bool SendRtcp(const uint8_t* packet, size_t length) {
75 return transport_->SendRtcp(packet, length);
76 }
77 ~TimedTransport() {}
78
79 private:
80 Transport* transport_;
81 TimeInterval* lifetime_;
82};
83
solenberg566ef242015-11-06 15:34:49 -080084AudioSendStream::AudioSendStream(
85 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +010086 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -070087 rtc::TaskQueue* worker_queue,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010088 ProcessThread* module_process_thread,
nisseb8f9a322017-03-27 05:36:15 -070089 RtpTransportControllerSendInterface* transport,
tereliuse035e2d2016-09-21 06:51:47 -070090 BitrateAllocator* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -080091 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -070092 RtcpRttStats* rtcp_rtt_stats,
Sam Zackrisson06953ba2018-02-01 16:53:16 +010093 const rtc::Optional<RtpState>& suspended_rtp_state,
94 TimeInterval* overall_call_lifetime)
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010095 : AudioSendStream(config,
96 audio_state,
97 worker_queue,
98 transport,
99 bitrate_allocator,
100 event_log,
101 rtcp_rtt_stats,
102 suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100103 overall_call_lifetime,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100104 CreateChannelAndProxy(audio_state.get(),
105 worker_queue,
106 module_process_thread)) {}
107
108AudioSendStream::AudioSendStream(
109 const webrtc::AudioSendStream::Config& config,
110 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
111 rtc::TaskQueue* worker_queue,
112 RtpTransportControllerSendInterface* transport,
113 BitrateAllocator* bitrate_allocator,
114 RtcEventLog* event_log,
115 RtcpRttStats* rtcp_rtt_stats,
116 const rtc::Optional<RtpState>& suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100117 TimeInterval* overall_call_lifetime,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100118 std::unique_ptr<voe::ChannelProxy> channel_proxy)
perkj26091b12016-09-01 01:17:40 -0700119 : worker_queue_(worker_queue),
ossu20a4b3f2017-04-27 02:08:52 -0700120 config_(Config(nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700121 audio_state_(audio_state),
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100122 channel_proxy_(std::move(channel_proxy)),
ossu20a4b3f2017-04-27 02:08:52 -0700123 event_log_(event_log),
michaeltf4caaab2017-01-16 23:55:07 -0800124 bitrate_allocator_(bitrate_allocator),
nisseb8f9a322017-03-27 05:36:15 -0700125 transport_(transport),
elad.alond12a8e12017-03-23 11:04:48 -0700126 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
127 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700128 kRecoverablePacketLossRateMinNumAckedPairs),
129 rtp_rtcp_module_(nullptr),
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100130 suspended_rtp_state_(suspended_rtp_state),
131 overall_call_lifetime_(overall_call_lifetime) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100132 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100133 RTC_DCHECK(worker_queue_);
134 RTC_DCHECK(audio_state_);
135 RTC_DCHECK(channel_proxy_);
136 RTC_DCHECK(bitrate_allocator_);
nisseb8f9a322017-03-27 05:36:15 -0700137 RTC_DCHECK(transport);
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100138 RTC_DCHECK(overall_call_lifetime_);
solenberg3a941542015-11-16 07:34:50 -0800139
ossu20a4b3f2017-04-27 02:08:52 -0700140 channel_proxy_->SetRtcEventLog(event_log_);
michaelt9332b7d2016-11-30 07:51:13 -0800141 channel_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
solenberg13725082015-11-25 08:16:52 -0800142 channel_proxy_->SetRTCPStatus(true);
ossuc3d4b482017-05-23 06:07:11 -0700143 RtpReceiver* rtpReceiver = nullptr; // Unused, but required for call.
144 channel_proxy_->GetRtpRtcp(&rtp_rtcp_module_, &rtpReceiver);
145 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700146
ossu20a4b3f2017-04-27 02:08:52 -0700147 ConfigureStream(this, config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700148
149 pacer_thread_checker_.DetachFromThread();
Danil Chapovalov90e1f532017-10-03 14:59:27 +0200150 // Signal congestion controller this object is ready for OnPacket* callbacks.
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100151 transport_->RegisterPacketFeedbackObserver(this);
solenbergc7a8b082015-10-16 14:35:07 -0700152}
153
154AudioSendStream::~AudioSendStream() {
elad.alond12a8e12017-03-23 11:04:48 -0700155 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100156 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100157 RTC_DCHECK(!sending_);
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100158 transport_->DeRegisterPacketFeedbackObserver(this);
solenberg1c239d42017-09-29 06:00:28 -0700159 channel_proxy_->RegisterTransport(nullptr);
nissefdbfdc92017-03-31 05:44:52 -0700160 channel_proxy_->ResetSenderCongestionControlObjects();
tereliuse035e2d2016-09-21 06:51:47 -0700161 channel_proxy_->SetRtcEventLog(nullptr);
michaelt9332b7d2016-11-30 07:51:13 -0800162 channel_proxy_->SetRtcpRttStats(nullptr);
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100163 // Lifetime can only be updated after deregistering
164 // |timed_send_transport_adapter_| in the underlying channel object to avoid
165 // data races in |active_lifetime_|.
166 overall_call_lifetime_->Extend(active_lifetime_);
solenbergc7a8b082015-10-16 14:35:07 -0700167}
168
eladalonabbc4302017-07-26 02:09:44 -0700169const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
170 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
171 return config_;
172}
173
ossu20a4b3f2017-04-27 02:08:52 -0700174void AudioSendStream::Reconfigure(
175 const webrtc::AudioSendStream::Config& new_config) {
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100176 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ossu20a4b3f2017-04-27 02:08:52 -0700177 ConfigureStream(this, new_config, false);
178}
179
Alex Narestcedd3512017-12-07 20:54:55 +0100180AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
181 const std::vector<RtpExtension>& extensions) {
182 ExtensionIds ids;
183 for (const auto& extension : extensions) {
184 if (extension.uri == RtpExtension::kAudioLevelUri) {
185 ids.audio_level = extension.id;
186 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
187 ids.transport_sequence_number = extension.id;
188 }
189 }
190 return ids;
191}
192
ossu20a4b3f2017-04-27 02:08:52 -0700193void AudioSendStream::ConfigureStream(
194 webrtc::internal::AudioSendStream* stream,
195 const webrtc::AudioSendStream::Config& new_config,
196 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100197 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
198 << new_config.ToString();
ossu20a4b3f2017-04-27 02:08:52 -0700199 const auto& channel_proxy = stream->channel_proxy_;
200 const auto& old_config = stream->config_;
201
202 if (first_time || old_config.rtp.ssrc != new_config.rtp.ssrc) {
203 channel_proxy->SetLocalSSRC(new_config.rtp.ssrc);
ossuc3d4b482017-05-23 06:07:11 -0700204 if (stream->suspended_rtp_state_) {
205 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
206 }
ossu20a4b3f2017-04-27 02:08:52 -0700207 }
208 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
209 channel_proxy->SetRTCP_CNAME(new_config.rtp.c_name);
210 }
211 // TODO(solenberg): Config NACK history window (which is a packet count),
212 // using the actual packet size for the configured codec.
213 if (first_time || old_config.rtp.nack.rtp_history_ms !=
214 new_config.rtp.nack.rtp_history_ms) {
215 channel_proxy->SetNACKStatus(new_config.rtp.nack.rtp_history_ms != 0,
216 new_config.rtp.nack.rtp_history_ms / 20);
217 }
218
219 if (first_time ||
220 new_config.send_transport != old_config.send_transport) {
221 if (old_config.send_transport) {
solenberg1c239d42017-09-29 06:00:28 -0700222 channel_proxy->RegisterTransport(nullptr);
ossu20a4b3f2017-04-27 02:08:52 -0700223 }
sazac58f8c02017-07-19 00:39:19 -0700224 if (new_config.send_transport) {
225 stream->timed_send_transport_adapter_.reset(new TimedTransport(
226 new_config.send_transport, &stream->active_lifetime_));
227 } else {
228 stream->timed_send_transport_adapter_.reset(nullptr);
229 }
solenberg1c239d42017-09-29 06:00:28 -0700230 channel_proxy->RegisterTransport(
sazac58f8c02017-07-19 00:39:19 -0700231 stream->timed_send_transport_adapter_.get());
ossu20a4b3f2017-04-27 02:08:52 -0700232 }
233
Alex Narestcedd3512017-12-07 20:54:55 +0100234 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
235 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
ossu20a4b3f2017-04-27 02:08:52 -0700236 // Audio level indication
237 if (first_time || new_ids.audio_level != old_ids.audio_level) {
238 channel_proxy->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
239 new_ids.audio_level);
240 }
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100241 bool transport_seq_num_id_changed =
242 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
243 if (first_time || transport_seq_num_id_changed) {
ossu1129df22017-06-30 01:38:56 -0700244 if (!first_time) {
ossu20a4b3f2017-04-27 02:08:52 -0700245 channel_proxy->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700246 }
247
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100248 RtcpBandwidthObserver* bandwidth_observer = nullptr;
249 bool has_transport_sequence_number = new_ids.transport_sequence_number != 0;
250 if (has_transport_sequence_number) {
ossu20a4b3f2017-04-27 02:08:52 -0700251 channel_proxy->EnableSendTransportSequenceNumber(
252 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100253 // Probing in application limited region is only used in combination with
254 // send side congestion control, wich depends on feedback packets which
255 // requires transport sequence numbers to be enabled.
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100256 stream->transport_->EnablePeriodicAlrProbing(true);
257 bandwidth_observer = stream->transport_->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700258 }
259
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100260 channel_proxy->RegisterSenderCongestionControlObjects(stream->transport_,
261 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700262 }
263
264 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100265 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700266 }
267
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100268 if (stream->sending_) {
269 ReconfigureBitrateObserver(stream, new_config);
270 }
ossu20a4b3f2017-04-27 02:08:52 -0700271 stream->config_ = new_config;
272}
273
solenberg3a941542015-11-16 07:34:50 -0800274void AudioSendStream::Start() {
elad.alond12a8e12017-03-23 11:04:48 -0700275 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100276 if (sending_) {
277 return;
278 }
279
Sebastian Jansson763e9472018-03-21 12:46:56 +0100280 bool has_transport_sequence_number =
281 FindExtensionIds(config_.rtp.extensions).transport_sequence_number != 0;
Alex Narestcedd3512017-12-07 20:54:55 +0100282 if (config_.min_bitrate_bps != -1 && config_.max_bitrate_bps != -1 &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100283 (has_transport_sequence_number ||
Alex Narestcedd3512017-12-07 20:54:55 +0100284 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Alex Narest78609d52017-10-20 10:37:47 +0200285 // Audio BWE is enabled.
286 transport_->packet_sender()->SetAccountForAudioPackets(true);
Seth Hampson24722b32017-12-22 09:36:42 -0800287 ConfigureBitrateObserver(config_.min_bitrate_bps, config_.max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100288 config_.bitrate_priority,
289 has_transport_sequence_number);
mflodman86cc6ff2016-07-26 04:44:06 -0700290 }
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100291 channel_proxy_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100292 sending_ = true;
293 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
294 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800295}
296
297void AudioSendStream::Stop() {
elad.alond12a8e12017-03-23 11:04:48 -0700298 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100299 if (!sending_) {
300 return;
301 }
302
ossu20a4b3f2017-04-27 02:08:52 -0700303 RemoveBitrateObserver();
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100304 channel_proxy_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100305 sending_ = false;
306 audio_state()->RemoveSendingStream(this);
307}
308
309void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
310 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
311 channel_proxy_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800312}
313
solenbergffbbcac2016-11-17 05:25:37 -0800314bool AudioSendStream::SendTelephoneEvent(int payload_type,
315 int payload_frequency, int event,
solenberg8842c3e2016-03-11 03:06:41 -0800316 int duration_ms) {
elad.alond12a8e12017-03-23 11:04:48 -0700317 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergffbbcac2016-11-17 05:25:37 -0800318 return channel_proxy_->SetSendTelephoneEventPayloadType(payload_type,
319 payload_frequency) &&
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100320 channel_proxy_->SendTelephoneEventOutband(event, duration_ms);
321}
322
solenberg94218532016-06-16 10:53:22 -0700323void AudioSendStream::SetMuted(bool muted) {
elad.alond12a8e12017-03-23 11:04:48 -0700324 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg94218532016-06-16 10:53:22 -0700325 channel_proxy_->SetInputMute(muted);
326}
327
solenbergc7a8b082015-10-16 14:35:07 -0700328webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100329 return GetStats(true);
330}
331
332webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
333 bool has_remote_tracks) const {
elad.alond12a8e12017-03-23 11:04:48 -0700334 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -0700335 webrtc::AudioSendStream::Stats stats;
336 stats.local_ssrc = config_.rtp.ssrc;
solenberg85a04962015-10-27 03:35:21 -0700337
solenberg358057b2015-11-27 10:46:42 -0800338 webrtc::CallStatistics call_stats = channel_proxy_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700339 stats.bytes_sent = call_stats.bytesSent;
340 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800341 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
342 // returns 0 to indicate an error value.
343 if (call_stats.rttMs > 0) {
344 stats.rtt_ms = call_stats.rttMs;
345 }
ossu20a4b3f2017-04-27 02:08:52 -0700346 if (config_.send_codec_spec) {
347 const auto& spec = *config_.send_codec_spec;
348 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100349 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700350
351 // Get data from the last remote RTCP report.
solenberg358057b2015-11-27 10:46:42 -0800352 for (const auto& block : channel_proxy_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800353 // Lookup report for send ssrc only.
354 if (block.source_SSRC == stats.local_ssrc) {
355 stats.packets_lost = block.cumulative_num_packets_lost;
356 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
357 stats.ext_seqnum = block.extended_highest_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700358 // Convert timestamps to milliseconds.
359 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800360 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700361 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700362 }
solenberg8b85de22015-11-16 09:48:04 -0800363 break;
solenberg85a04962015-10-27 03:35:21 -0700364 }
365 }
366 }
367
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100368 AudioState::Stats input_stats = audio_state()->GetAudioInputStats();
369 stats.audio_level = input_stats.audio_level;
370 stats.total_input_energy = input_stats.total_energy;
371 stats.total_input_duration = input_stats.total_duration;
solenberg796b8f92017-03-01 17:02:23 -0800372
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100373 stats.typing_noise_detected = audio_state()->typing_noise_detected();
ivoce1198e02017-09-08 08:13:19 -0700374 stats.ana_statistics = channel_proxy_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100375 RTC_DCHECK(audio_state_->audio_processing());
376 stats.apm_statistics =
377 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700378
379 return stats;
380}
381
pbos1ba8d392016-05-01 20:18:34 -0700382void AudioSendStream::SignalNetworkState(NetworkState state) {
elad.alond12a8e12017-03-23 11:04:48 -0700383 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700384}
385
386bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
387 // TODO(solenberg): Tests call this function on a network thread, libjingle
388 // calls on the worker thread. We should move towards always using a network
389 // thread. Then this check can be enabled.
elad.alond12a8e12017-03-23 11:04:48 -0700390 // RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700391 return channel_proxy_->ReceivedRTCPPacket(packet, length);
392}
393
mflodman86cc6ff2016-07-26 04:44:06 -0700394uint32_t AudioSendStream::OnBitrateUpdated(uint32_t bitrate_bps,
395 uint8_t fraction_loss,
minyue78b4d562016-11-30 04:47:39 -0800396 int64_t rtt,
minyue93e45222017-05-18 14:32:41 -0700397 int64_t bwe_period_ms) {
stefanfca900a2017-04-10 03:53:00 -0700398 // A send stream may be allocated a bitrate of zero if the allocator decides
399 // to disable it. For now we ignore this decision and keep sending on min
400 // bitrate.
401 if (bitrate_bps == 0) {
402 bitrate_bps = config_.min_bitrate_bps;
403 }
mflodman86cc6ff2016-07-26 04:44:06 -0700404 RTC_DCHECK_GE(bitrate_bps,
minyue10cbb462016-11-07 09:29:22 -0800405 static_cast<uint32_t>(config_.min_bitrate_bps));
mflodman86cc6ff2016-07-26 04:44:06 -0700406 // The bitrate allocator might allocate an higher than max configured bitrate
407 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
minyue10cbb462016-11-07 09:29:22 -0800408 const uint32_t max_bitrate_bps = config_.max_bitrate_bps;
mflodman86cc6ff2016-07-26 04:44:06 -0700409 if (bitrate_bps > max_bitrate_bps)
410 bitrate_bps = max_bitrate_bps;
411
minyue93e45222017-05-18 14:32:41 -0700412 channel_proxy_->SetBitrate(bitrate_bps, bwe_period_ms);
mflodman86cc6ff2016-07-26 04:44:06 -0700413
414 // The amount of audio protection is not exposed by the encoder, hence
415 // always returning 0.
416 return 0;
417}
418
elad.alond12a8e12017-03-23 11:04:48 -0700419void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
420 RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread());
421 // Only packets that belong to this stream are of interest.
422 if (ssrc == config_.rtp.ssrc) {
423 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700424 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700425 // setting both PLR and RPLR to unknown. Consider (during upcoming
426 // refactoring) passing an indication of such an event.
427 packet_loss_tracker_.OnPacketAdded(seq_num, rtc::TimeMillis());
428 }
429}
430
431void AudioSendStream::OnPacketFeedbackVector(
432 const std::vector<PacketFeedback>& packet_feedback_vector) {
eladalon3651fdd2017-08-24 07:26:25 -0700433 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
elad.alond12a8e12017-03-23 11:04:48 -0700434 rtc::Optional<float> plr;
elad.alondadb4dc2017-03-23 15:29:50 -0700435 rtc::Optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700436 {
437 rtc::CritScope lock(&packet_loss_tracker_cs_);
438 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
439 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700440 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700441 }
eladalonedd6eea2017-05-25 00:15:35 -0700442 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700443 // the previously sent value is no longer relevant. This will be taken care
444 // of with some refactoring which is now being done.
445 if (plr) {
446 channel_proxy_->OnTwccBasedUplinkPacketLossRate(*plr);
447 }
elad.alondadb4dc2017-03-23 15:29:50 -0700448 if (rplr) {
449 channel_proxy_->OnRecoverableUplinkPacketLossRate(*rplr);
450 }
elad.alond12a8e12017-03-23 11:04:48 -0700451}
452
michaelt79e05882016-11-08 02:50:09 -0800453void AudioSendStream::SetTransportOverhead(int transport_overhead_per_packet) {
elad.alond12a8e12017-03-23 11:04:48 -0700454 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
michaelt79e05882016-11-08 02:50:09 -0800455 channel_proxy_->SetTransportOverhead(transport_overhead_per_packet);
456}
457
ossuc3d4b482017-05-23 06:07:11 -0700458RtpState AudioSendStream::GetRtpState() const {
459 return rtp_rtcp_module_->GetRtpState();
460}
461
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100462const voe::ChannelProxy& AudioSendStream::GetChannelProxy() const {
463 RTC_DCHECK(channel_proxy_.get());
464 return *channel_proxy_.get();
465}
466
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100467internal::AudioState* AudioSendStream::audio_state() {
468 internal::AudioState* audio_state =
469 static_cast<internal::AudioState*>(audio_state_.get());
470 RTC_DCHECK(audio_state);
471 return audio_state;
472}
473
474const internal::AudioState* AudioSendStream::audio_state() const {
475 internal::AudioState* audio_state =
476 static_cast<internal::AudioState*>(audio_state_.get());
477 RTC_DCHECK(audio_state);
478 return audio_state;
479}
480
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100481void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
482 size_t num_channels) {
483 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
484 encoder_sample_rate_hz_ = sample_rate_hz;
485 encoder_num_channels_ = num_channels;
486 if (sending_) {
487 // Update AudioState's information about the stream.
488 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
489 }
490}
491
minyue7a973442016-10-20 03:27:12 -0700492// Apply current codec settings to a single voe::Channel used for sending.
ossu20a4b3f2017-04-27 02:08:52 -0700493bool AudioSendStream::SetupSendCodec(AudioSendStream* stream,
494 const Config& new_config) {
495 RTC_DCHECK(new_config.send_codec_spec);
496 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700497
498 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700499 std::unique_ptr<AudioEncoder> encoder =
500 new_config.encoder_factory->MakeAudioEncoder(spec.payload_type,
Karl Wiberg98cd8102018-03-05 15:01:10 +0100501 spec.format, rtc::nullopt);
minyue7a973442016-10-20 03:27:12 -0700502
ossu20a4b3f2017-04-27 02:08:52 -0700503 if (!encoder) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100504 RTC_DLOG(LS_ERROR) << "Unable to create encoder for " << spec.format;
ossu20a4b3f2017-04-27 02:08:52 -0700505 return false;
506 }
507 // If a bitrate has been specified for the codec, use it over the
508 // codec's default.
509 if (spec.target_bitrate_bps) {
510 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700511 }
512
ossu20a4b3f2017-04-27 02:08:52 -0700513 // Enable ANA if configured (currently only used by Opus).
514 if (new_config.audio_network_adaptor_config) {
515 if (encoder->EnableAudioNetworkAdaptor(
516 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100517 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
518 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700519 } else {
520 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700521 }
minyue7a973442016-10-20 03:27:12 -0700522 }
523
ossu20a4b3f2017-04-27 02:08:52 -0700524 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
525 if (spec.cng_payload_type) {
526 AudioEncoderCng::Config cng_config;
527 cng_config.num_channels = encoder->NumChannels();
528 cng_config.payload_type = *spec.cng_payload_type;
529 cng_config.speech_encoder = std::move(encoder);
530 cng_config.vad_mode = Vad::kVadNormal;
531 encoder.reset(new AudioEncoderCng(std::move(cng_config)));
ossu3b9ff382017-04-27 08:03:42 -0700532
533 stream->RegisterCngPayloadType(
534 *spec.cng_payload_type,
535 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700536 }
ossu20a4b3f2017-04-27 02:08:52 -0700537
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100538 stream->StoreEncoderProperties(encoder->SampleRateHz(),
539 encoder->NumChannels());
ossu20a4b3f2017-04-27 02:08:52 -0700540 stream->channel_proxy_->SetEncoder(new_config.send_codec_spec->payload_type,
541 std::move(encoder));
minyue7a973442016-10-20 03:27:12 -0700542 return true;
543}
544
ossu20a4b3f2017-04-27 02:08:52 -0700545bool AudioSendStream::ReconfigureSendCodec(AudioSendStream* stream,
546 const Config& new_config) {
547 const auto& old_config = stream->config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200548
549 if (!new_config.send_codec_spec) {
550 // We cannot de-configure a send codec. So we will do nothing.
551 // By design, the send codec should have not been configured.
552 RTC_DCHECK(!old_config.send_codec_spec);
553 return true;
554 }
555
556 if (new_config.send_codec_spec == old_config.send_codec_spec &&
557 new_config.audio_network_adaptor_config ==
558 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700559 return true;
560 }
561
562 // If we have no encoder, or the format or payload type's changed, create a
563 // new encoder.
564 if (!old_config.send_codec_spec ||
565 new_config.send_codec_spec->format !=
566 old_config.send_codec_spec->format ||
567 new_config.send_codec_spec->payload_type !=
568 old_config.send_codec_spec->payload_type) {
569 return SetupSendCodec(stream, new_config);
570 }
571
ossu20a4b3f2017-04-27 02:08:52 -0700572 const rtc::Optional<int>& new_target_bitrate_bps =
573 new_config.send_codec_spec->target_bitrate_bps;
574 // If a bitrate has been specified for the codec, use it over the
575 // codec's default.
576 if (new_target_bitrate_bps &&
577 new_target_bitrate_bps !=
578 old_config.send_codec_spec->target_bitrate_bps) {
579 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
580 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
581 });
582 }
583
584 ReconfigureANA(stream, new_config);
585 ReconfigureCNG(stream, new_config);
586
587 return true;
588}
589
590void AudioSendStream::ReconfigureANA(AudioSendStream* stream,
591 const Config& new_config) {
592 if (new_config.audio_network_adaptor_config ==
593 stream->config_.audio_network_adaptor_config) {
594 return;
595 }
596 if (new_config.audio_network_adaptor_config) {
597 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
598 if (encoder->EnableAudioNetworkAdaptor(
599 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100600 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
601 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700602 } else {
603 RTC_NOTREACHED();
604 }
605 });
606 } else {
607 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
608 encoder->DisableAudioNetworkAdaptor();
609 });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100610 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
611 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700612 }
613}
614
615void AudioSendStream::ReconfigureCNG(AudioSendStream* stream,
616 const Config& new_config) {
617 if (new_config.send_codec_spec->cng_payload_type ==
618 stream->config_.send_codec_spec->cng_payload_type) {
619 return;
620 }
621
ossu3b9ff382017-04-27 08:03:42 -0700622 // Register the CNG payload type if it's been added, don't do anything if CNG
623 // is removed. Payload types must not be redefined.
624 if (new_config.send_codec_spec->cng_payload_type) {
625 stream->RegisterCngPayloadType(
626 *new_config.send_codec_spec->cng_payload_type,
627 new_config.send_codec_spec->format.clockrate_hz);
628 }
629
ossu20a4b3f2017-04-27 02:08:52 -0700630 // Wrap or unwrap the encoder in an AudioEncoderCNG.
631 stream->channel_proxy_->ModifyEncoder(
632 [&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
633 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
634 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
635 if (!sub_encoders.empty()) {
636 // Replace enc with its sub encoder. We need to put the sub
637 // encoder in a temporary first, since otherwise the old value
638 // of enc would be destroyed before the new value got assigned,
639 // which would be bad since the new value is a part of the old
640 // value.
641 auto tmp = std::move(sub_encoders[0]);
642 old_encoder = std::move(tmp);
643 }
644 if (new_config.send_codec_spec->cng_payload_type) {
645 AudioEncoderCng::Config config;
646 config.speech_encoder = std::move(old_encoder);
647 config.num_channels = config.speech_encoder->NumChannels();
648 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
649 config.vad_mode = Vad::kVadNormal;
650 encoder_ptr->reset(new AudioEncoderCng(std::move(config)));
651 } else {
652 *encoder_ptr = std::move(old_encoder);
653 }
654 });
655}
656
657void AudioSendStream::ReconfigureBitrateObserver(
658 AudioSendStream* stream,
659 const webrtc::AudioSendStream::Config& new_config) {
660 // Since the Config's default is for both of these to be -1, this test will
661 // allow us to configure the bitrate observer if the new config has bitrate
662 // limits set, but would only have us call RemoveBitrateObserver if we were
663 // previously configured with bitrate limits.
Alex Narestcedd3512017-12-07 20:54:55 +0100664 int new_transport_seq_num_id =
665 FindExtensionIds(new_config.rtp.extensions).transport_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700666 if (stream->config_.min_bitrate_bps == new_config.min_bitrate_bps &&
Alex Narestcedd3512017-12-07 20:54:55 +0100667 stream->config_.max_bitrate_bps == new_config.max_bitrate_bps &&
Seth Hampson24722b32017-12-22 09:36:42 -0800668 stream->config_.bitrate_priority == new_config.bitrate_priority &&
Alex Narestcedd3512017-12-07 20:54:55 +0100669 (FindExtensionIds(stream->config_.rtp.extensions)
670 .transport_sequence_number == new_transport_seq_num_id ||
671 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
ossu20a4b3f2017-04-27 02:08:52 -0700672 return;
673 }
674
Sebastian Jansson763e9472018-03-21 12:46:56 +0100675 bool has_transport_sequence_number = new_transport_seq_num_id != 0;
Alex Narestcedd3512017-12-07 20:54:55 +0100676 if (new_config.min_bitrate_bps != -1 && new_config.max_bitrate_bps != -1 &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100677 (has_transport_sequence_number ||
Alex Narestcedd3512017-12-07 20:54:55 +0100678 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Sebastian Jansson763e9472018-03-21 12:46:56 +0100679 stream->ConfigureBitrateObserver(
680 new_config.min_bitrate_bps, new_config.max_bitrate_bps,
681 new_config.bitrate_priority, has_transport_sequence_number);
ossu20a4b3f2017-04-27 02:08:52 -0700682 } else {
683 stream->RemoveBitrateObserver();
684 }
685}
686
687void AudioSendStream::ConfigureBitrateObserver(int min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800688 int max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100689 double bitrate_priority,
690 bool has_packet_feedback) {
ossu20a4b3f2017-04-27 02:08:52 -0700691 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
692 RTC_DCHECK_GE(max_bitrate_bps, min_bitrate_bps);
693 rtc::Event thread_sync_event(false /* manual_reset */, false);
694 worker_queue_->PostTask([&] {
695 // We may get a callback immediately as the observer is registered, so make
696 // sure the bitrate limits in config_ are up-to-date.
697 config_.min_bitrate_bps = min_bitrate_bps;
698 config_.max_bitrate_bps = max_bitrate_bps;
Seth Hampson24722b32017-12-22 09:36:42 -0800699 config_.bitrate_priority = bitrate_priority;
700 // This either updates the current observer or adds a new observer.
ossu20a4b3f2017-04-27 02:08:52 -0700701 bitrate_allocator_->AddObserver(this, min_bitrate_bps, max_bitrate_bps, 0,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100702 true, config_.track_id, bitrate_priority,
703 has_packet_feedback);
ossu20a4b3f2017-04-27 02:08:52 -0700704 thread_sync_event.Set();
705 });
706 thread_sync_event.Wait(rtc::Event::kForever);
707}
708
709void AudioSendStream::RemoveBitrateObserver() {
710 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
711 rtc::Event thread_sync_event(false /* manual_reset */, false);
712 worker_queue_->PostTask([this, &thread_sync_event] {
713 bitrate_allocator_->RemoveObserver(this);
714 thread_sync_event.Set();
715 });
716 thread_sync_event.Wait(rtc::Event::kForever);
717}
718
ossu3b9ff382017-04-27 08:03:42 -0700719void AudioSendStream::RegisterCngPayloadType(int payload_type,
720 int clockrate_hz) {
ossu3b9ff382017-04-27 08:03:42 -0700721 const CodecInst codec = {payload_type, "CN", clockrate_hz, 0, 1, 0};
ossuc3d4b482017-05-23 06:07:11 -0700722 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
723 rtp_rtcp_module_->DeRegisterSendPayload(codec.pltype);
724 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100725 RTC_DLOG(LS_ERROR) << "RegisterCngPayloadType() failed to register CN to "
726 "RTP/RTCP module";
ossu3b9ff382017-04-27 08:03:42 -0700727 }
728 }
729}
solenbergc7a8b082015-10-16 14:35:07 -0700730} // namespace internal
731} // namespace webrtc