blob: 8ed78eb461908c2ad379068a8992e63642a1d3eb [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"
Jonas Olssonabbe8412018-04-03 13:40:05 +020026#include "rtc_base/strings/audio_format_to_string.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/task_queue.h"
28#include "rtc_base/timeutils.h"
Alex Narestcedd3512017-12-07 20:54:55 +010029#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070030
31namespace webrtc {
solenbergc7a8b082015-10-16 14:35:07 -070032namespace internal {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010033namespace {
eladalonedd6eea2017-05-25 00:15:35 -070034// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070035constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
36constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
37constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
38
ossu20a4b3f2017-04-27 02:08:52 -070039void CallEncoder(const std::unique_ptr<voe::ChannelProxy>& channel_proxy,
40 rtc::FunctionView<void(AudioEncoder*)> lambda) {
41 channel_proxy->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
42 RTC_DCHECK(encoder_ptr);
43 lambda(encoder_ptr->get());
44 });
45}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010046
47std::unique_ptr<voe::ChannelProxy> CreateChannelAndProxy(
48 webrtc::AudioState* audio_state,
49 rtc::TaskQueue* worker_queue,
Tommi5f223652018-03-26 13:28:26 +020050 ProcessThread* module_process_thread,
51 RtcpRttStats* rtcp_rtt_stats) {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010052 RTC_DCHECK(audio_state);
53 internal::AudioState* internal_audio_state =
54 static_cast<internal::AudioState*>(audio_state);
Tommi5f223652018-03-26 13:28:26 +020055 return std::unique_ptr<voe::ChannelProxy>(
56 new voe::ChannelProxy(std::unique_ptr<voe::Channel>(new voe::Channel(
57 worker_queue, module_process_thread,
58 internal_audio_state->audio_device_module(), rtcp_rtt_stats))));
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010059}
ossu20a4b3f2017-04-27 02:08:52 -070060} // namespace
61
Sam Zackrisson06953ba2018-02-01 16:53:16 +010062// Helper class to track the actively sending lifetime of this stream.
sazac58f8c02017-07-19 00:39:19 -070063class AudioSendStream::TimedTransport : public Transport {
64 public:
65 TimedTransport(Transport* transport, TimeInterval* time_interval)
66 : transport_(transport), lifetime_(time_interval) {}
67 bool SendRtp(const uint8_t* packet,
68 size_t length,
69 const PacketOptions& options) {
70 if (lifetime_) {
71 lifetime_->Extend();
72 }
73 return transport_->SendRtp(packet, length, options);
74 }
75 bool SendRtcp(const uint8_t* packet, size_t length) {
76 return transport_->SendRtcp(packet, length);
77 }
78 ~TimedTransport() {}
79
80 private:
81 Transport* transport_;
82 TimeInterval* lifetime_;
83};
84
solenberg566ef242015-11-06 15:34:49 -080085AudioSendStream::AudioSendStream(
86 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +010087 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -070088 rtc::TaskQueue* worker_queue,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010089 ProcessThread* module_process_thread,
nisseb8f9a322017-03-27 05:36:15 -070090 RtpTransportControllerSendInterface* transport,
tereliuse035e2d2016-09-21 06:51:47 -070091 BitrateAllocator* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -080092 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -070093 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020094 const absl::optional<RtpState>& suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +010095 TimeInterval* overall_call_lifetime)
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010096 : AudioSendStream(config,
97 audio_state,
98 worker_queue,
99 transport,
100 bitrate_allocator,
101 event_log,
102 rtcp_rtt_stats,
103 suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100104 overall_call_lifetime,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100105 CreateChannelAndProxy(audio_state.get(),
106 worker_queue,
Tommi5f223652018-03-26 13:28:26 +0200107 module_process_thread,
108 rtcp_rtt_stats)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100109
110AudioSendStream::AudioSendStream(
111 const webrtc::AudioSendStream::Config& config,
112 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
113 rtc::TaskQueue* worker_queue,
114 RtpTransportControllerSendInterface* transport,
115 BitrateAllocator* bitrate_allocator,
116 RtcEventLog* event_log,
117 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200118 const absl::optional<RtpState>& suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100119 TimeInterval* overall_call_lifetime,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100120 std::unique_ptr<voe::ChannelProxy> channel_proxy)
perkj26091b12016-09-01 01:17:40 -0700121 : worker_queue_(worker_queue),
ossu20a4b3f2017-04-27 02:08:52 -0700122 config_(Config(nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700123 audio_state_(audio_state),
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100124 channel_proxy_(std::move(channel_proxy)),
ossu20a4b3f2017-04-27 02:08:52 -0700125 event_log_(event_log),
michaeltf4caaab2017-01-16 23:55:07 -0800126 bitrate_allocator_(bitrate_allocator),
nisseb8f9a322017-03-27 05:36:15 -0700127 transport_(transport),
elad.alond12a8e12017-03-23 11:04:48 -0700128 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
129 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700130 kRecoverablePacketLossRateMinNumAckedPairs),
131 rtp_rtcp_module_(nullptr),
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100132 suspended_rtp_state_(suspended_rtp_state),
133 overall_call_lifetime_(overall_call_lifetime) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100134 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100135 RTC_DCHECK(worker_queue_);
136 RTC_DCHECK(audio_state_);
137 RTC_DCHECK(channel_proxy_);
138 RTC_DCHECK(bitrate_allocator_);
nisseb8f9a322017-03-27 05:36:15 -0700139 RTC_DCHECK(transport);
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100140 RTC_DCHECK(overall_call_lifetime_);
solenberg3a941542015-11-16 07:34:50 -0800141
ossu20a4b3f2017-04-27 02:08:52 -0700142 channel_proxy_->SetRtcEventLog(event_log_);
solenberg13725082015-11-25 08:16:52 -0800143 channel_proxy_->SetRTCPStatus(true);
ossuc3d4b482017-05-23 06:07:11 -0700144 RtpReceiver* rtpReceiver = nullptr; // Unused, but required for call.
145 channel_proxy_->GetRtpRtcp(&rtp_rtcp_module_, &rtpReceiver);
146 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700147
ossu20a4b3f2017-04-27 02:08:52 -0700148 ConfigureStream(this, config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700149
150 pacer_thread_checker_.DetachFromThread();
Danil Chapovalov90e1f532017-10-03 14:59:27 +0200151 // Signal congestion controller this object is ready for OnPacket* callbacks.
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100152 transport_->RegisterPacketFeedbackObserver(this);
solenbergc7a8b082015-10-16 14:35:07 -0700153}
154
155AudioSendStream::~AudioSendStream() {
elad.alond12a8e12017-03-23 11:04:48 -0700156 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100157 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100158 RTC_DCHECK(!sending_);
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100159 transport_->DeRegisterPacketFeedbackObserver(this);
solenberg1c239d42017-09-29 06:00:28 -0700160 channel_proxy_->RegisterTransport(nullptr);
nissefdbfdc92017-03-31 05:44:52 -0700161 channel_proxy_->ResetSenderCongestionControlObjects();
tereliuse035e2d2016-09-21 06:51:47 -0700162 channel_proxy_->SetRtcEventLog(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;
Steve Antonbb50ce52018-03-26 10:24:32 -0700188 } else if (extension.uri == RtpExtension::kMidUri) {
189 ids.mid = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100190 }
191 }
192 return ids;
193}
194
ossu20a4b3f2017-04-27 02:08:52 -0700195void AudioSendStream::ConfigureStream(
196 webrtc::internal::AudioSendStream* stream,
197 const webrtc::AudioSendStream::Config& new_config,
198 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100199 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
200 << new_config.ToString();
ossu20a4b3f2017-04-27 02:08:52 -0700201 const auto& channel_proxy = stream->channel_proxy_;
202 const auto& old_config = stream->config_;
203
204 if (first_time || old_config.rtp.ssrc != new_config.rtp.ssrc) {
205 channel_proxy->SetLocalSSRC(new_config.rtp.ssrc);
ossuc3d4b482017-05-23 06:07:11 -0700206 if (stream->suspended_rtp_state_) {
207 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
208 }
ossu20a4b3f2017-04-27 02:08:52 -0700209 }
210 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
211 channel_proxy->SetRTCP_CNAME(new_config.rtp.c_name);
212 }
213 // TODO(solenberg): Config NACK history window (which is a packet count),
214 // using the actual packet size for the configured codec.
215 if (first_time || old_config.rtp.nack.rtp_history_ms !=
216 new_config.rtp.nack.rtp_history_ms) {
217 channel_proxy->SetNACKStatus(new_config.rtp.nack.rtp_history_ms != 0,
218 new_config.rtp.nack.rtp_history_ms / 20);
219 }
220
221 if (first_time ||
222 new_config.send_transport != old_config.send_transport) {
223 if (old_config.send_transport) {
solenberg1c239d42017-09-29 06:00:28 -0700224 channel_proxy->RegisterTransport(nullptr);
ossu20a4b3f2017-04-27 02:08:52 -0700225 }
sazac58f8c02017-07-19 00:39:19 -0700226 if (new_config.send_transport) {
227 stream->timed_send_transport_adapter_.reset(new TimedTransport(
228 new_config.send_transport, &stream->active_lifetime_));
229 } else {
230 stream->timed_send_transport_adapter_.reset(nullptr);
231 }
solenberg1c239d42017-09-29 06:00:28 -0700232 channel_proxy->RegisterTransport(
sazac58f8c02017-07-19 00:39:19 -0700233 stream->timed_send_transport_adapter_.get());
ossu20a4b3f2017-04-27 02:08:52 -0700234 }
235
Alex Narestcedd3512017-12-07 20:54:55 +0100236 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
237 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
ossu20a4b3f2017-04-27 02:08:52 -0700238 // Audio level indication
239 if (first_time || new_ids.audio_level != old_ids.audio_level) {
240 channel_proxy->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
241 new_ids.audio_level);
242 }
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100243 bool transport_seq_num_id_changed =
244 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Alex Narest867e5102018-06-12 13:40:18 +0200245 if (first_time ||
246 (transport_seq_num_id_changed &&
247 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC"))) {
ossu1129df22017-06-30 01:38:56 -0700248 if (!first_time) {
ossu20a4b3f2017-04-27 02:08:52 -0700249 channel_proxy->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700250 }
251
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100252 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Alex Narest867e5102018-06-12 13:40:18 +0200253 bool has_transport_sequence_number =
254 new_ids.transport_sequence_number != 0 &&
255 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC");
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100256 if (has_transport_sequence_number) {
ossu20a4b3f2017-04-27 02:08:52 -0700257 channel_proxy->EnableSendTransportSequenceNumber(
258 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100259 // Probing in application limited region is only used in combination with
260 // send side congestion control, wich depends on feedback packets which
261 // requires transport sequence numbers to be enabled.
Sebastian Janssone4be6da2018-02-15 16:51:41 +0100262 stream->transport_->EnablePeriodicAlrProbing(true);
263 bandwidth_observer = stream->transport_->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700264 }
265
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100266 channel_proxy->RegisterSenderCongestionControlObjects(stream->transport_,
267 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700268 }
269
Steve Antonbb50ce52018-03-26 10:24:32 -0700270 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700271 if ((first_time || new_ids.mid != old_ids.mid ||
272 new_config.rtp.mid != old_config.rtp.mid) &&
273 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Steve Antonbb50ce52018-03-26 10:24:32 -0700274 channel_proxy->SetMid(new_config.rtp.mid, new_ids.mid);
275 }
276
ossu20a4b3f2017-04-27 02:08:52 -0700277 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100278 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700279 }
280
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100281 if (stream->sending_) {
282 ReconfigureBitrateObserver(stream, new_config);
283 }
ossu20a4b3f2017-04-27 02:08:52 -0700284 stream->config_ = new_config;
285}
286
solenberg3a941542015-11-16 07:34:50 -0800287void AudioSendStream::Start() {
elad.alond12a8e12017-03-23 11:04:48 -0700288 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100289 if (sending_) {
290 return;
291 }
292
Sebastian Jansson763e9472018-03-21 12:46:56 +0100293 bool has_transport_sequence_number =
Alex Narest867e5102018-06-12 13:40:18 +0200294 FindExtensionIds(config_.rtp.extensions).transport_sequence_number != 0 &&
295 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC");
Alex Narestcedd3512017-12-07 20:54:55 +0100296 if (config_.min_bitrate_bps != -1 && config_.max_bitrate_bps != -1 &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100297 (has_transport_sequence_number ||
Alex Narestcedd3512017-12-07 20:54:55 +0100298 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Alex Narest78609d52017-10-20 10:37:47 +0200299 // Audio BWE is enabled.
300 transport_->packet_sender()->SetAccountForAudioPackets(true);
Seth Hampson24722b32017-12-22 09:36:42 -0800301 ConfigureBitrateObserver(config_.min_bitrate_bps, config_.max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100302 config_.bitrate_priority,
303 has_transport_sequence_number);
mflodman86cc6ff2016-07-26 04:44:06 -0700304 }
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100305 channel_proxy_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100306 sending_ = true;
307 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
308 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800309}
310
311void AudioSendStream::Stop() {
elad.alond12a8e12017-03-23 11:04:48 -0700312 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100313 if (!sending_) {
314 return;
315 }
316
ossu20a4b3f2017-04-27 02:08:52 -0700317 RemoveBitrateObserver();
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100318 channel_proxy_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100319 sending_ = false;
320 audio_state()->RemoveSendingStream(this);
321}
322
323void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
324 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
325 channel_proxy_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800326}
327
solenbergffbbcac2016-11-17 05:25:37 -0800328bool AudioSendStream::SendTelephoneEvent(int payload_type,
329 int payload_frequency, int event,
solenberg8842c3e2016-03-11 03:06:41 -0800330 int duration_ms) {
elad.alond12a8e12017-03-23 11:04:48 -0700331 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergffbbcac2016-11-17 05:25:37 -0800332 return channel_proxy_->SetSendTelephoneEventPayloadType(payload_type,
333 payload_frequency) &&
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100334 channel_proxy_->SendTelephoneEventOutband(event, duration_ms);
335}
336
solenberg94218532016-06-16 10:53:22 -0700337void AudioSendStream::SetMuted(bool muted) {
elad.alond12a8e12017-03-23 11:04:48 -0700338 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg94218532016-06-16 10:53:22 -0700339 channel_proxy_->SetInputMute(muted);
340}
341
solenbergc7a8b082015-10-16 14:35:07 -0700342webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100343 return GetStats(true);
344}
345
346webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
347 bool has_remote_tracks) const {
elad.alond12a8e12017-03-23 11:04:48 -0700348 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -0700349 webrtc::AudioSendStream::Stats stats;
350 stats.local_ssrc = config_.rtp.ssrc;
solenberg85a04962015-10-27 03:35:21 -0700351
solenberg358057b2015-11-27 10:46:42 -0800352 webrtc::CallStatistics call_stats = channel_proxy_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700353 stats.bytes_sent = call_stats.bytesSent;
354 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800355 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
356 // returns 0 to indicate an error value.
357 if (call_stats.rttMs > 0) {
358 stats.rtt_ms = call_stats.rttMs;
359 }
ossu20a4b3f2017-04-27 02:08:52 -0700360 if (config_.send_codec_spec) {
361 const auto& spec = *config_.send_codec_spec;
362 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100363 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700364
365 // Get data from the last remote RTCP report.
solenberg358057b2015-11-27 10:46:42 -0800366 for (const auto& block : channel_proxy_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800367 // Lookup report for send ssrc only.
368 if (block.source_SSRC == stats.local_ssrc) {
369 stats.packets_lost = block.cumulative_num_packets_lost;
370 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
371 stats.ext_seqnum = block.extended_highest_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700372 // Convert timestamps to milliseconds.
373 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800374 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700375 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700376 }
solenberg8b85de22015-11-16 09:48:04 -0800377 break;
solenberg85a04962015-10-27 03:35:21 -0700378 }
379 }
380 }
381
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100382 AudioState::Stats input_stats = audio_state()->GetAudioInputStats();
383 stats.audio_level = input_stats.audio_level;
384 stats.total_input_energy = input_stats.total_energy;
385 stats.total_input_duration = input_stats.total_duration;
solenberg796b8f92017-03-01 17:02:23 -0800386
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100387 stats.typing_noise_detected = audio_state()->typing_noise_detected();
ivoce1198e02017-09-08 08:13:19 -0700388 stats.ana_statistics = channel_proxy_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100389 RTC_DCHECK(audio_state_->audio_processing());
390 stats.apm_statistics =
391 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700392
393 return stats;
394}
395
pbos1ba8d392016-05-01 20:18:34 -0700396void AudioSendStream::SignalNetworkState(NetworkState state) {
elad.alond12a8e12017-03-23 11:04:48 -0700397 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700398}
399
400bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
401 // TODO(solenberg): Tests call this function on a network thread, libjingle
402 // calls on the worker thread. We should move towards always using a network
403 // thread. Then this check can be enabled.
elad.alond12a8e12017-03-23 11:04:48 -0700404 // RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700405 return channel_proxy_->ReceivedRTCPPacket(packet, length);
406}
407
mflodman86cc6ff2016-07-26 04:44:06 -0700408uint32_t AudioSendStream::OnBitrateUpdated(uint32_t bitrate_bps,
409 uint8_t fraction_loss,
minyue78b4d562016-11-30 04:47:39 -0800410 int64_t rtt,
minyue93e45222017-05-18 14:32:41 -0700411 int64_t bwe_period_ms) {
stefanfca900a2017-04-10 03:53:00 -0700412 // A send stream may be allocated a bitrate of zero if the allocator decides
413 // to disable it. For now we ignore this decision and keep sending on min
414 // bitrate.
415 if (bitrate_bps == 0) {
416 bitrate_bps = config_.min_bitrate_bps;
417 }
mflodman86cc6ff2016-07-26 04:44:06 -0700418 RTC_DCHECK_GE(bitrate_bps,
minyue10cbb462016-11-07 09:29:22 -0800419 static_cast<uint32_t>(config_.min_bitrate_bps));
mflodman86cc6ff2016-07-26 04:44:06 -0700420 // The bitrate allocator might allocate an higher than max configured bitrate
421 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
minyue10cbb462016-11-07 09:29:22 -0800422 const uint32_t max_bitrate_bps = config_.max_bitrate_bps;
mflodman86cc6ff2016-07-26 04:44:06 -0700423 if (bitrate_bps > max_bitrate_bps)
424 bitrate_bps = max_bitrate_bps;
425
minyue93e45222017-05-18 14:32:41 -0700426 channel_proxy_->SetBitrate(bitrate_bps, bwe_period_ms);
mflodman86cc6ff2016-07-26 04:44:06 -0700427
428 // The amount of audio protection is not exposed by the encoder, hence
429 // always returning 0.
430 return 0;
431}
432
elad.alond12a8e12017-03-23 11:04:48 -0700433void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
434 RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread());
435 // Only packets that belong to this stream are of interest.
436 if (ssrc == config_.rtp.ssrc) {
437 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700438 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700439 // setting both PLR and RPLR to unknown. Consider (during upcoming
440 // refactoring) passing an indication of such an event.
441 packet_loss_tracker_.OnPacketAdded(seq_num, rtc::TimeMillis());
442 }
443}
444
445void AudioSendStream::OnPacketFeedbackVector(
446 const std::vector<PacketFeedback>& packet_feedback_vector) {
eladalon3651fdd2017-08-24 07:26:25 -0700447 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200448 absl::optional<float> plr;
449 absl::optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700450 {
451 rtc::CritScope lock(&packet_loss_tracker_cs_);
452 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
453 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700454 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700455 }
eladalonedd6eea2017-05-25 00:15:35 -0700456 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700457 // the previously sent value is no longer relevant. This will be taken care
458 // of with some refactoring which is now being done.
459 if (plr) {
460 channel_proxy_->OnTwccBasedUplinkPacketLossRate(*plr);
461 }
elad.alondadb4dc2017-03-23 15:29:50 -0700462 if (rplr) {
463 channel_proxy_->OnRecoverableUplinkPacketLossRate(*rplr);
464 }
elad.alond12a8e12017-03-23 11:04:48 -0700465}
466
michaelt79e05882016-11-08 02:50:09 -0800467void AudioSendStream::SetTransportOverhead(int transport_overhead_per_packet) {
elad.alond12a8e12017-03-23 11:04:48 -0700468 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
michaelt79e05882016-11-08 02:50:09 -0800469 channel_proxy_->SetTransportOverhead(transport_overhead_per_packet);
470}
471
ossuc3d4b482017-05-23 06:07:11 -0700472RtpState AudioSendStream::GetRtpState() const {
473 return rtp_rtcp_module_->GetRtpState();
474}
475
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100476const voe::ChannelProxy& AudioSendStream::GetChannelProxy() const {
477 RTC_DCHECK(channel_proxy_.get());
478 return *channel_proxy_.get();
479}
480
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100481internal::AudioState* AudioSendStream::audio_state() {
482 internal::AudioState* audio_state =
483 static_cast<internal::AudioState*>(audio_state_.get());
484 RTC_DCHECK(audio_state);
485 return audio_state;
486}
487
488const internal::AudioState* AudioSendStream::audio_state() const {
489 internal::AudioState* audio_state =
490 static_cast<internal::AudioState*>(audio_state_.get());
491 RTC_DCHECK(audio_state);
492 return audio_state;
493}
494
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100495void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
496 size_t num_channels) {
497 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
498 encoder_sample_rate_hz_ = sample_rate_hz;
499 encoder_num_channels_ = num_channels;
500 if (sending_) {
501 // Update AudioState's information about the stream.
502 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
503 }
504}
505
minyue7a973442016-10-20 03:27:12 -0700506// Apply current codec settings to a single voe::Channel used for sending.
ossu20a4b3f2017-04-27 02:08:52 -0700507bool AudioSendStream::SetupSendCodec(AudioSendStream* stream,
508 const Config& new_config) {
509 RTC_DCHECK(new_config.send_codec_spec);
510 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700511
512 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700513 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100514 new_config.encoder_factory->MakeAudioEncoder(
515 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700516
ossu20a4b3f2017-04-27 02:08:52 -0700517 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200518 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
519 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700520 return false;
521 }
522 // If a bitrate has been specified for the codec, use it over the
523 // codec's default.
524 if (spec.target_bitrate_bps) {
525 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700526 }
527
ossu20a4b3f2017-04-27 02:08:52 -0700528 // Enable ANA if configured (currently only used by Opus).
529 if (new_config.audio_network_adaptor_config) {
530 if (encoder->EnableAudioNetworkAdaptor(
531 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100532 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
533 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700534 } else {
535 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700536 }
minyue7a973442016-10-20 03:27:12 -0700537 }
538
ossu20a4b3f2017-04-27 02:08:52 -0700539 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
540 if (spec.cng_payload_type) {
541 AudioEncoderCng::Config cng_config;
542 cng_config.num_channels = encoder->NumChannels();
543 cng_config.payload_type = *spec.cng_payload_type;
544 cng_config.speech_encoder = std::move(encoder);
545 cng_config.vad_mode = Vad::kVadNormal;
546 encoder.reset(new AudioEncoderCng(std::move(cng_config)));
ossu3b9ff382017-04-27 08:03:42 -0700547
548 stream->RegisterCngPayloadType(
549 *spec.cng_payload_type,
550 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700551 }
ossu20a4b3f2017-04-27 02:08:52 -0700552
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100553 stream->StoreEncoderProperties(encoder->SampleRateHz(),
554 encoder->NumChannels());
ossu20a4b3f2017-04-27 02:08:52 -0700555 stream->channel_proxy_->SetEncoder(new_config.send_codec_spec->payload_type,
556 std::move(encoder));
minyue7a973442016-10-20 03:27:12 -0700557 return true;
558}
559
ossu20a4b3f2017-04-27 02:08:52 -0700560bool AudioSendStream::ReconfigureSendCodec(AudioSendStream* stream,
561 const Config& new_config) {
562 const auto& old_config = stream->config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200563
564 if (!new_config.send_codec_spec) {
565 // We cannot de-configure a send codec. So we will do nothing.
566 // By design, the send codec should have not been configured.
567 RTC_DCHECK(!old_config.send_codec_spec);
568 return true;
569 }
570
571 if (new_config.send_codec_spec == old_config.send_codec_spec &&
572 new_config.audio_network_adaptor_config ==
573 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700574 return true;
575 }
576
577 // If we have no encoder, or the format or payload type's changed, create a
578 // new encoder.
579 if (!old_config.send_codec_spec ||
580 new_config.send_codec_spec->format !=
581 old_config.send_codec_spec->format ||
582 new_config.send_codec_spec->payload_type !=
583 old_config.send_codec_spec->payload_type) {
584 return SetupSendCodec(stream, new_config);
585 }
586
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200587 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700588 new_config.send_codec_spec->target_bitrate_bps;
589 // If a bitrate has been specified for the codec, use it over the
590 // codec's default.
591 if (new_target_bitrate_bps &&
592 new_target_bitrate_bps !=
593 old_config.send_codec_spec->target_bitrate_bps) {
594 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
595 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
596 });
597 }
598
599 ReconfigureANA(stream, new_config);
600 ReconfigureCNG(stream, new_config);
601
602 return true;
603}
604
605void AudioSendStream::ReconfigureANA(AudioSendStream* stream,
606 const Config& new_config) {
607 if (new_config.audio_network_adaptor_config ==
608 stream->config_.audio_network_adaptor_config) {
609 return;
610 }
611 if (new_config.audio_network_adaptor_config) {
612 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
613 if (encoder->EnableAudioNetworkAdaptor(
614 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100615 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
616 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700617 } else {
618 RTC_NOTREACHED();
619 }
620 });
621 } else {
622 CallEncoder(stream->channel_proxy_, [&](AudioEncoder* encoder) {
623 encoder->DisableAudioNetworkAdaptor();
624 });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100625 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
626 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700627 }
628}
629
630void AudioSendStream::ReconfigureCNG(AudioSendStream* stream,
631 const Config& new_config) {
632 if (new_config.send_codec_spec->cng_payload_type ==
633 stream->config_.send_codec_spec->cng_payload_type) {
634 return;
635 }
636
ossu3b9ff382017-04-27 08:03:42 -0700637 // Register the CNG payload type if it's been added, don't do anything if CNG
638 // is removed. Payload types must not be redefined.
639 if (new_config.send_codec_spec->cng_payload_type) {
640 stream->RegisterCngPayloadType(
641 *new_config.send_codec_spec->cng_payload_type,
642 new_config.send_codec_spec->format.clockrate_hz);
643 }
644
ossu20a4b3f2017-04-27 02:08:52 -0700645 // Wrap or unwrap the encoder in an AudioEncoderCNG.
646 stream->channel_proxy_->ModifyEncoder(
647 [&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
648 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
649 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
650 if (!sub_encoders.empty()) {
651 // Replace enc with its sub encoder. We need to put the sub
652 // encoder in a temporary first, since otherwise the old value
653 // of enc would be destroyed before the new value got assigned,
654 // which would be bad since the new value is a part of the old
655 // value.
656 auto tmp = std::move(sub_encoders[0]);
657 old_encoder = std::move(tmp);
658 }
659 if (new_config.send_codec_spec->cng_payload_type) {
660 AudioEncoderCng::Config config;
661 config.speech_encoder = std::move(old_encoder);
662 config.num_channels = config.speech_encoder->NumChannels();
663 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
664 config.vad_mode = Vad::kVadNormal;
665 encoder_ptr->reset(new AudioEncoderCng(std::move(config)));
666 } else {
667 *encoder_ptr = std::move(old_encoder);
668 }
669 });
670}
671
672void AudioSendStream::ReconfigureBitrateObserver(
673 AudioSendStream* stream,
674 const webrtc::AudioSendStream::Config& new_config) {
675 // Since the Config's default is for both of these to be -1, this test will
676 // allow us to configure the bitrate observer if the new config has bitrate
677 // limits set, but would only have us call RemoveBitrateObserver if we were
678 // previously configured with bitrate limits.
Alex Narestcedd3512017-12-07 20:54:55 +0100679 int new_transport_seq_num_id =
680 FindExtensionIds(new_config.rtp.extensions).transport_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700681 if (stream->config_.min_bitrate_bps == new_config.min_bitrate_bps &&
Alex Narestcedd3512017-12-07 20:54:55 +0100682 stream->config_.max_bitrate_bps == new_config.max_bitrate_bps &&
Seth Hampson24722b32017-12-22 09:36:42 -0800683 stream->config_.bitrate_priority == new_config.bitrate_priority &&
Alex Narestcedd3512017-12-07 20:54:55 +0100684 (FindExtensionIds(stream->config_.rtp.extensions)
685 .transport_sequence_number == new_transport_seq_num_id ||
686 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
ossu20a4b3f2017-04-27 02:08:52 -0700687 return;
688 }
689
Sebastian Jansson763e9472018-03-21 12:46:56 +0100690 bool has_transport_sequence_number = new_transport_seq_num_id != 0;
Alex Narestcedd3512017-12-07 20:54:55 +0100691 if (new_config.min_bitrate_bps != -1 && new_config.max_bitrate_bps != -1 &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100692 (has_transport_sequence_number ||
Alex Narestcedd3512017-12-07 20:54:55 +0100693 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Sebastian Jansson763e9472018-03-21 12:46:56 +0100694 stream->ConfigureBitrateObserver(
695 new_config.min_bitrate_bps, new_config.max_bitrate_bps,
696 new_config.bitrate_priority, has_transport_sequence_number);
ossu20a4b3f2017-04-27 02:08:52 -0700697 } else {
698 stream->RemoveBitrateObserver();
699 }
700}
701
702void AudioSendStream::ConfigureBitrateObserver(int min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800703 int max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100704 double bitrate_priority,
705 bool has_packet_feedback) {
ossu20a4b3f2017-04-27 02:08:52 -0700706 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
707 RTC_DCHECK_GE(max_bitrate_bps, min_bitrate_bps);
708 rtc::Event thread_sync_event(false /* manual_reset */, false);
709 worker_queue_->PostTask([&] {
710 // We may get a callback immediately as the observer is registered, so make
711 // sure the bitrate limits in config_ are up-to-date.
712 config_.min_bitrate_bps = min_bitrate_bps;
713 config_.max_bitrate_bps = max_bitrate_bps;
Seth Hampson24722b32017-12-22 09:36:42 -0800714 config_.bitrate_priority = bitrate_priority;
715 // This either updates the current observer or adds a new observer.
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200716 bitrate_allocator_->AddObserver(
717 this, MediaStreamAllocationConfig{
718 static_cast<uint32_t>(min_bitrate_bps),
719 static_cast<uint32_t>(max_bitrate_bps), 0, true,
720 config_.track_id, bitrate_priority, has_packet_feedback});
ossu20a4b3f2017-04-27 02:08:52 -0700721 thread_sync_event.Set();
722 });
723 thread_sync_event.Wait(rtc::Event::kForever);
724}
725
726void AudioSendStream::RemoveBitrateObserver() {
727 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
728 rtc::Event thread_sync_event(false /* manual_reset */, false);
729 worker_queue_->PostTask([this, &thread_sync_event] {
730 bitrate_allocator_->RemoveObserver(this);
731 thread_sync_event.Set();
732 });
733 thread_sync_event.Wait(rtc::Event::kForever);
734}
735
ossu3b9ff382017-04-27 08:03:42 -0700736void AudioSendStream::RegisterCngPayloadType(int payload_type,
737 int clockrate_hz) {
ossu3b9ff382017-04-27 08:03:42 -0700738 const CodecInst codec = {payload_type, "CN", clockrate_hz, 0, 1, 0};
ossuc3d4b482017-05-23 06:07:11 -0700739 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
740 rtp_rtcp_module_->DeRegisterSendPayload(codec.pltype);
741 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100742 RTC_DLOG(LS_ERROR) << "RegisterCngPayloadType() failed to register CN to "
743 "RTP/RTCP module";
ossu3b9ff382017-04-27 08:03:42 -0700744 }
745 }
746}
solenbergc7a8b082015-10-16 14:35:07 -0700747} // namespace internal
748} // namespace webrtc