blob: 80c2c6b43537dfd97d89eaee5de7aea9df3e356b [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"
22#include "modules/bitrate_controller/include/bitrate_controller.h"
23#include "modules/congestion_controller/include/send_side_congestion_controller.h"
24#include "modules/pacing/paced_sender.h"
25#include "rtc_base/checks.h"
26#include "rtc_base/event.h"
27#include "rtc_base/function_view.h"
28#include "rtc_base/logging.h"
29#include "rtc_base/task_queue.h"
30#include "rtc_base/timeutils.h"
Alex Narestcedd3512017-12-07 20:54:55 +010031#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070032
33namespace webrtc {
solenbergc7a8b082015-10-16 14:35:07 -070034namespace internal {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010035namespace {
eladalonedd6eea2017-05-25 00:15:35 -070036// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070037constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
38constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
39constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
40
ossu20a4b3f2017-04-27 02:08:52 -070041void CallEncoder(const std::unique_ptr<voe::ChannelProxy>& channel_proxy,
42 rtc::FunctionView<void(AudioEncoder*)> lambda) {
43 channel_proxy->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
44 RTC_DCHECK(encoder_ptr);
45 lambda(encoder_ptr->get());
46 });
47}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010048
49std::unique_ptr<voe::ChannelProxy> CreateChannelAndProxy(
50 webrtc::AudioState* audio_state,
51 rtc::TaskQueue* worker_queue,
52 ProcessThread* module_process_thread) {
53 RTC_DCHECK(audio_state);
54 internal::AudioState* internal_audio_state =
55 static_cast<internal::AudioState*>(audio_state);
56 return std::unique_ptr<voe::ChannelProxy>(new voe::ChannelProxy(
57 std::unique_ptr<voe::Channel>(new voe::Channel(
58 worker_queue,
59 module_process_thread,
60 internal_audio_state->audio_device_module()))));
61}
ossu20a4b3f2017-04-27 02:08:52 -070062} // namespace
63
sazac58f8c02017-07-19 00:39:19 -070064// TODO(saza): Move this declaration further down when we can use
65// std::make_unique.
66class AudioSendStream::TimedTransport : public Transport {
67 public:
68 TimedTransport(Transport* transport, TimeInterval* time_interval)
69 : transport_(transport), lifetime_(time_interval) {}
70 bool SendRtp(const uint8_t* packet,
71 size_t length,
72 const PacketOptions& options) {
73 if (lifetime_) {
74 lifetime_->Extend();
75 }
76 return transport_->SendRtp(packet, length, options);
77 }
78 bool SendRtcp(const uint8_t* packet, size_t length) {
79 return transport_->SendRtcp(packet, length);
80 }
81 ~TimedTransport() {}
82
83 private:
84 Transport* transport_;
85 TimeInterval* lifetime_;
86};
87
solenberg566ef242015-11-06 15:34:49 -080088AudioSendStream::AudioSendStream(
89 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +010090 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -070091 rtc::TaskQueue* worker_queue,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010092 ProcessThread* module_process_thread,
nisseb8f9a322017-03-27 05:36:15 -070093 RtpTransportControllerSendInterface* transport,
tereliuse035e2d2016-09-21 06:51:47 -070094 BitrateAllocator* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -080095 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -070096 RtcpRttStats* rtcp_rtt_stats,
97 const rtc::Optional<RtpState>& suspended_rtp_state)
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010098 : AudioSendStream(config,
99 audio_state,
100 worker_queue,
101 transport,
102 bitrate_allocator,
103 event_log,
104 rtcp_rtt_stats,
105 suspended_rtp_state,
106 CreateChannelAndProxy(audio_state.get(),
107 worker_queue,
108 module_process_thread)) {}
109
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,
118 const rtc::Optional<RtpState>& suspended_rtp_state,
119 std::unique_ptr<voe::ChannelProxy> channel_proxy)
perkj26091b12016-09-01 01:17:40 -0700120 : worker_queue_(worker_queue),
ossu20a4b3f2017-04-27 02:08:52 -0700121 config_(Config(nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700122 audio_state_(audio_state),
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100123 channel_proxy_(std::move(channel_proxy)),
ossu20a4b3f2017-04-27 02:08:52 -0700124 event_log_(event_log),
michaeltf4caaab2017-01-16 23:55:07 -0800125 bitrate_allocator_(bitrate_allocator),
nisseb8f9a322017-03-27 05:36:15 -0700126 transport_(transport),
elad.alond12a8e12017-03-23 11:04:48 -0700127 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
128 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700129 kRecoverablePacketLossRateMinNumAckedPairs),
130 rtp_rtcp_module_(nullptr),
131 suspended_rtp_state_(suspended_rtp_state) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100132 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.ToString();
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);
138 RTC_DCHECK(transport->send_side_cc());
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.
151 transport_->send_side_cc()->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());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100156 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.ToString();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100157 RTC_DCHECK(!sending_);
nisseb8f9a322017-03-27 05:36:15 -0700158 transport_->send_side_cc()->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);
solenbergc7a8b082015-10-16 14:35:07 -0700163}
164
eladalonabbc4302017-07-26 02:09:44 -0700165const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
166 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
167 return config_;
168}
169
ossu20a4b3f2017-04-27 02:08:52 -0700170void AudioSendStream::Reconfigure(
171 const webrtc::AudioSendStream::Config& new_config) {
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100172 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ossu20a4b3f2017-04-27 02:08:52 -0700173 ConfigureStream(this, new_config, false);
174}
175
Alex Narestcedd3512017-12-07 20:54:55 +0100176AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
177 const std::vector<RtpExtension>& extensions) {
178 ExtensionIds ids;
179 for (const auto& extension : extensions) {
180 if (extension.uri == RtpExtension::kAudioLevelUri) {
181 ids.audio_level = extension.id;
182 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
183 ids.transport_sequence_number = extension.id;
184 }
185 }
186 return ids;
187}
188
ossu20a4b3f2017-04-27 02:08:52 -0700189void AudioSendStream::ConfigureStream(
190 webrtc::internal::AudioSendStream* stream,
191 const webrtc::AudioSendStream::Config& new_config,
192 bool first_time) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100193 RTC_LOG(LS_INFO) << "AudioSendStream::Configuring: " << new_config.ToString();
ossu20a4b3f2017-04-27 02:08:52 -0700194 const auto& channel_proxy = stream->channel_proxy_;
195 const auto& old_config = stream->config_;
196
197 if (first_time || old_config.rtp.ssrc != new_config.rtp.ssrc) {
198 channel_proxy->SetLocalSSRC(new_config.rtp.ssrc);
ossuc3d4b482017-05-23 06:07:11 -0700199 if (stream->suspended_rtp_state_) {
200 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
201 }
ossu20a4b3f2017-04-27 02:08:52 -0700202 }
203 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
204 channel_proxy->SetRTCP_CNAME(new_config.rtp.c_name);
205 }
206 // TODO(solenberg): Config NACK history window (which is a packet count),
207 // using the actual packet size for the configured codec.
208 if (first_time || old_config.rtp.nack.rtp_history_ms !=
209 new_config.rtp.nack.rtp_history_ms) {
210 channel_proxy->SetNACKStatus(new_config.rtp.nack.rtp_history_ms != 0,
211 new_config.rtp.nack.rtp_history_ms / 20);
212 }
213
214 if (first_time ||
215 new_config.send_transport != old_config.send_transport) {
216 if (old_config.send_transport) {
solenberg1c239d42017-09-29 06:00:28 -0700217 channel_proxy->RegisterTransport(nullptr);
ossu20a4b3f2017-04-27 02:08:52 -0700218 }
sazac58f8c02017-07-19 00:39:19 -0700219 if (new_config.send_transport) {
220 stream->timed_send_transport_adapter_.reset(new TimedTransport(
221 new_config.send_transport, &stream->active_lifetime_));
222 } else {
223 stream->timed_send_transport_adapter_.reset(nullptr);
224 }
solenberg1c239d42017-09-29 06:00:28 -0700225 channel_proxy->RegisterTransport(
sazac58f8c02017-07-19 00:39:19 -0700226 stream->timed_send_transport_adapter_.get());
ossu20a4b3f2017-04-27 02:08:52 -0700227 }
228
Alex Narestcedd3512017-12-07 20:54:55 +0100229 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
230 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
ossu20a4b3f2017-04-27 02:08:52 -0700231 // Audio level indication
232 if (first_time || new_ids.audio_level != old_ids.audio_level) {
233 channel_proxy->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
234 new_ids.audio_level);
235 }
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100236 bool transport_seq_num_id_changed =
237 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
238 if (first_time || transport_seq_num_id_changed) {
ossu1129df22017-06-30 01:38:56 -0700239 if (!first_time) {
ossu20a4b3f2017-04-27 02:08:52 -0700240 channel_proxy->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700241 }
242
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100243 RtcpBandwidthObserver* bandwidth_observer = nullptr;
244 bool has_transport_sequence_number = new_ids.transport_sequence_number != 0;
245 if (has_transport_sequence_number) {
ossu20a4b3f2017-04-27 02:08:52 -0700246 channel_proxy->EnableSendTransportSequenceNumber(
247 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100248 // Probing in application limited region is only used in combination with
249 // send side congestion control, wich depends on feedback packets which
250 // requires transport sequence numbers to be enabled.
ossu20a4b3f2017-04-27 02:08:52 -0700251 stream->transport_->send_side_cc()->EnablePeriodicAlrProbing(true);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100252 bandwidth_observer =
253 stream->transport_->send_side_cc()->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700254 }
255
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100256 channel_proxy->RegisterSenderCongestionControlObjects(stream->transport_,
257 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700258 }
259
260 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100261 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700262 }
263
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100264 if (stream->sending_) {
265 ReconfigureBitrateObserver(stream, new_config);
266 }
ossu20a4b3f2017-04-27 02:08:52 -0700267 stream->config_ = new_config;
268}
269
solenberg3a941542015-11-16 07:34:50 -0800270void AudioSendStream::Start() {
elad.alond12a8e12017-03-23 11:04:48 -0700271 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100272 if (sending_) {
273 return;
274 }
275
Alex Narestcedd3512017-12-07 20:54:55 +0100276 if (config_.min_bitrate_bps != -1 && config_.max_bitrate_bps != -1 &&
277 (FindExtensionIds(config_.rtp.extensions).transport_sequence_number !=
278 0 ||
279 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Alex Narest78609d52017-10-20 10:37:47 +0200280 // Audio BWE is enabled.
281 transport_->packet_sender()->SetAccountForAudioPackets(true);
Seth Hampson24722b32017-12-22 09:36:42 -0800282 ConfigureBitrateObserver(config_.min_bitrate_bps, config_.max_bitrate_bps,
283 config_.bitrate_priority);
mflodman86cc6ff2016-07-26 04:44:06 -0700284 }
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100285 channel_proxy_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100286 sending_ = true;
287 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
288 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800289}
290
291void AudioSendStream::Stop() {
elad.alond12a8e12017-03-23 11:04:48 -0700292 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100293 if (!sending_) {
294 return;
295 }
296
ossu20a4b3f2017-04-27 02:08:52 -0700297 RemoveBitrateObserver();
Fredrik Solenbergaaedf752017-12-18 13:09:12 +0100298 channel_proxy_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100299 sending_ = false;
300 audio_state()->RemoveSendingStream(this);
301}
302
303void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
304 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
305 channel_proxy_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800306}
307
solenbergffbbcac2016-11-17 05:25:37 -0800308bool AudioSendStream::SendTelephoneEvent(int payload_type,
309 int payload_frequency, int event,
solenberg8842c3e2016-03-11 03:06:41 -0800310 int duration_ms) {
elad.alond12a8e12017-03-23 11:04:48 -0700311 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenbergffbbcac2016-11-17 05:25:37 -0800312 return channel_proxy_->SetSendTelephoneEventPayloadType(payload_type,
313 payload_frequency) &&
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100314 channel_proxy_->SendTelephoneEventOutband(event, duration_ms);
315}
316
solenberg94218532016-06-16 10:53:22 -0700317void AudioSendStream::SetMuted(bool muted) {
elad.alond12a8e12017-03-23 11:04:48 -0700318 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg94218532016-06-16 10:53:22 -0700319 channel_proxy_->SetInputMute(muted);
320}
321
solenbergc7a8b082015-10-16 14:35:07 -0700322webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100323 return GetStats(true);
324}
325
326webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
327 bool has_remote_tracks) const {
elad.alond12a8e12017-03-23 11:04:48 -0700328 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -0700329 webrtc::AudioSendStream::Stats stats;
330 stats.local_ssrc = config_.rtp.ssrc;
solenberg85a04962015-10-27 03:35:21 -0700331
solenberg358057b2015-11-27 10:46:42 -0800332 webrtc::CallStatistics call_stats = channel_proxy_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700333 stats.bytes_sent = call_stats.bytesSent;
334 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800335 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
336 // returns 0 to indicate an error value.
337 if (call_stats.rttMs > 0) {
338 stats.rtt_ms = call_stats.rttMs;
339 }
ossu20a4b3f2017-04-27 02:08:52 -0700340 if (config_.send_codec_spec) {
341 const auto& spec = *config_.send_codec_spec;
342 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100343 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700344
345 // Get data from the last remote RTCP report.
solenberg358057b2015-11-27 10:46:42 -0800346 for (const auto& block : channel_proxy_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800347 // Lookup report for send ssrc only.
348 if (block.source_SSRC == stats.local_ssrc) {
349 stats.packets_lost = block.cumulative_num_packets_lost;
350 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
351 stats.ext_seqnum = block.extended_highest_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700352 // Convert timestamps to milliseconds.
353 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800354 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700355 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700356 }
solenberg8b85de22015-11-16 09:48:04 -0800357 break;
solenberg85a04962015-10-27 03:35:21 -0700358 }
359 }
360 }
361
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100362 AudioState::Stats input_stats = audio_state()->GetAudioInputStats();
363 stats.audio_level = input_stats.audio_level;
364 stats.total_input_energy = input_stats.total_energy;
365 stats.total_input_duration = input_stats.total_duration;
solenberg796b8f92017-03-01 17:02:23 -0800366
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100367 stats.typing_noise_detected = audio_state()->typing_noise_detected();
ivoce1198e02017-09-08 08:13:19 -0700368 stats.ana_statistics = channel_proxy_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100369 RTC_DCHECK(audio_state_->audio_processing());
370 stats.apm_statistics =
371 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700372
373 return stats;
374}
375
pbos1ba8d392016-05-01 20:18:34 -0700376void AudioSendStream::SignalNetworkState(NetworkState state) {
elad.alond12a8e12017-03-23 11:04:48 -0700377 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700378}
379
380bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
381 // TODO(solenberg): Tests call this function on a network thread, libjingle
382 // calls on the worker thread. We should move towards always using a network
383 // thread. Then this check can be enabled.
elad.alond12a8e12017-03-23 11:04:48 -0700384 // RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700385 return channel_proxy_->ReceivedRTCPPacket(packet, length);
386}
387
mflodman86cc6ff2016-07-26 04:44:06 -0700388uint32_t AudioSendStream::OnBitrateUpdated(uint32_t bitrate_bps,
389 uint8_t fraction_loss,
minyue78b4d562016-11-30 04:47:39 -0800390 int64_t rtt,
minyue93e45222017-05-18 14:32:41 -0700391 int64_t bwe_period_ms) {
stefanfca900a2017-04-10 03:53:00 -0700392 // A send stream may be allocated a bitrate of zero if the allocator decides
393 // to disable it. For now we ignore this decision and keep sending on min
394 // bitrate.
395 if (bitrate_bps == 0) {
396 bitrate_bps = config_.min_bitrate_bps;
397 }
mflodman86cc6ff2016-07-26 04:44:06 -0700398 RTC_DCHECK_GE(bitrate_bps,
minyue10cbb462016-11-07 09:29:22 -0800399 static_cast<uint32_t>(config_.min_bitrate_bps));
mflodman86cc6ff2016-07-26 04:44:06 -0700400 // The bitrate allocator might allocate an higher than max configured bitrate
401 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
minyue10cbb462016-11-07 09:29:22 -0800402 const uint32_t max_bitrate_bps = config_.max_bitrate_bps;
mflodman86cc6ff2016-07-26 04:44:06 -0700403 if (bitrate_bps > max_bitrate_bps)
404 bitrate_bps = max_bitrate_bps;
405
minyue93e45222017-05-18 14:32:41 -0700406 channel_proxy_->SetBitrate(bitrate_bps, bwe_period_ms);
mflodman86cc6ff2016-07-26 04:44:06 -0700407
408 // The amount of audio protection is not exposed by the encoder, hence
409 // always returning 0.
410 return 0;
411}
412
elad.alond12a8e12017-03-23 11:04:48 -0700413void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
414 RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread());
415 // Only packets that belong to this stream are of interest.
416 if (ssrc == config_.rtp.ssrc) {
417 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700418 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700419 // setting both PLR and RPLR to unknown. Consider (during upcoming
420 // refactoring) passing an indication of such an event.
421 packet_loss_tracker_.OnPacketAdded(seq_num, rtc::TimeMillis());
422 }
423}
424
425void AudioSendStream::OnPacketFeedbackVector(
426 const std::vector<PacketFeedback>& packet_feedback_vector) {
eladalon3651fdd2017-08-24 07:26:25 -0700427 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
elad.alond12a8e12017-03-23 11:04:48 -0700428 rtc::Optional<float> plr;
elad.alondadb4dc2017-03-23 15:29:50 -0700429 rtc::Optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700430 {
431 rtc::CritScope lock(&packet_loss_tracker_cs_);
432 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
433 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700434 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700435 }
eladalonedd6eea2017-05-25 00:15:35 -0700436 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700437 // the previously sent value is no longer relevant. This will be taken care
438 // of with some refactoring which is now being done.
439 if (plr) {
440 channel_proxy_->OnTwccBasedUplinkPacketLossRate(*plr);
441 }
elad.alondadb4dc2017-03-23 15:29:50 -0700442 if (rplr) {
443 channel_proxy_->OnRecoverableUplinkPacketLossRate(*rplr);
444 }
elad.alond12a8e12017-03-23 11:04:48 -0700445}
446
michaelt79e05882016-11-08 02:50:09 -0800447void AudioSendStream::SetTransportOverhead(int transport_overhead_per_packet) {
elad.alond12a8e12017-03-23 11:04:48 -0700448 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
nisseb8f9a322017-03-27 05:36:15 -0700449 transport_->send_side_cc()->SetTransportOverhead(
450 transport_overhead_per_packet);
michaelt79e05882016-11-08 02:50:09 -0800451 channel_proxy_->SetTransportOverhead(transport_overhead_per_packet);
452}
453
ossuc3d4b482017-05-23 06:07:11 -0700454RtpState AudioSendStream::GetRtpState() const {
455 return rtp_rtcp_module_->GetRtpState();
456}
457
sazac58f8c02017-07-19 00:39:19 -0700458const TimeInterval& AudioSendStream::GetActiveLifetime() const {
459 return active_lifetime_;
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,
501 spec.format);
minyue7a973442016-10-20 03:27:12 -0700502
ossu20a4b3f2017-04-27 02:08:52 -0700503 if (!encoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100504 RTC_LOG(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_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100517 RTC_LOG(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_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100600 RTC_LOG(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 });
Mirko Bonadei675513b2017-11-09 11:09:25 +0100610 RTC_LOG(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
Alex Narestcedd3512017-12-07 20:54:55 +0100675 if (new_config.min_bitrate_bps != -1 && new_config.max_bitrate_bps != -1 &&
676 (new_transport_seq_num_id != 0 ||
677 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
ossu20a4b3f2017-04-27 02:08:52 -0700678 stream->ConfigureBitrateObserver(new_config.min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800679 new_config.max_bitrate_bps,
680 new_config.bitrate_priority);
ossu20a4b3f2017-04-27 02:08:52 -0700681 } else {
682 stream->RemoveBitrateObserver();
683 }
684}
685
686void AudioSendStream::ConfigureBitrateObserver(int min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800687 int max_bitrate_bps,
688 double bitrate_priority) {
ossu20a4b3f2017-04-27 02:08:52 -0700689 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
690 RTC_DCHECK_GE(max_bitrate_bps, min_bitrate_bps);
691 rtc::Event thread_sync_event(false /* manual_reset */, false);
692 worker_queue_->PostTask([&] {
693 // We may get a callback immediately as the observer is registered, so make
694 // sure the bitrate limits in config_ are up-to-date.
695 config_.min_bitrate_bps = min_bitrate_bps;
696 config_.max_bitrate_bps = max_bitrate_bps;
Seth Hampson24722b32017-12-22 09:36:42 -0800697 config_.bitrate_priority = bitrate_priority;
698 // This either updates the current observer or adds a new observer.
ossu20a4b3f2017-04-27 02:08:52 -0700699 bitrate_allocator_->AddObserver(this, min_bitrate_bps, max_bitrate_bps, 0,
Seth Hampson24722b32017-12-22 09:36:42 -0800700 true, config_.track_id, bitrate_priority);
ossu20a4b3f2017-04-27 02:08:52 -0700701 thread_sync_event.Set();
702 });
703 thread_sync_event.Wait(rtc::Event::kForever);
704}
705
706void AudioSendStream::RemoveBitrateObserver() {
707 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
708 rtc::Event thread_sync_event(false /* manual_reset */, false);
709 worker_queue_->PostTask([this, &thread_sync_event] {
710 bitrate_allocator_->RemoveObserver(this);
711 thread_sync_event.Set();
712 });
713 thread_sync_event.Wait(rtc::Event::kForever);
714}
715
ossu3b9ff382017-04-27 08:03:42 -0700716void AudioSendStream::RegisterCngPayloadType(int payload_type,
717 int clockrate_hz) {
ossu3b9ff382017-04-27 08:03:42 -0700718 const CodecInst codec = {payload_type, "CN", clockrate_hz, 0, 1, 0};
ossuc3d4b482017-05-23 06:07:11 -0700719 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
720 rtp_rtcp_module_->DeRegisterSendPayload(codec.pltype);
721 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_ERROR) << "RegisterCngPayloadType() failed to register CN to "
723 "RTP/RTCP module";
ossu3b9ff382017-04-27 08:03:42 -0700724 }
725 }
726}
solenbergc7a8b082015-10-16 14:35:07 -0700727} // namespace internal
728} // namespace webrtc