blob: 22bd9831e44931a5df57a93a9808513b959cc300 [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
Mirko Bonadei317a1f02019-09-17 17:06:18 +020013#include <memory>
solenbergc7a8b082015-10-16 14:35:07 -070014#include <string>
ossu20a4b3f2017-04-27 02:08:52 -070015#include <utility>
16#include <vector>
solenbergc7a8b082015-10-16 14:35:07 -070017
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "api/audio_codecs/audio_encoder.h"
19#include "api/audio_codecs/audio_encoder_factory.h"
20#include "api/audio_codecs/audio_format.h"
21#include "api/call/transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "api/crypto/frame_encryptor_interface.h"
Artem Titov741daaf2019-03-21 14:37:36 +010023#include "api/function_view.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020024#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller65f17ca2019-09-12 13:59:36 +020025#include "api/transport/media/media_transport_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "audio/audio_state.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "audio/channel_send.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "audio/conversion.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "call/rtp_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey988cc082018-10-23 12:03:01 +020031#include "common_audio/vad/include/vad.h"
Oskar Sundbom56ef3052018-10-30 16:11:02 +010032#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
Oskar Sundbom56ef3052018-10-30 16:11:02 +010033#include "logging/rtc_event_log/rtc_stream_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
Yves Gerey988cc082018-10-23 12:03:01 +020035#include "modules/audio_processing/include/audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/checks.h"
37#include "rtc_base/event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/logging.h"
Jonas Olssonabbe8412018-04-03 13:40:05 +020039#include "rtc_base/strings/audio_format_to_string.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/task_queue.h"
Alex Narestcedd3512017-12-07 20:54:55 +010041#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070042
43namespace webrtc {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010044namespace {
eladalonedd6eea2017-05-25 00:15:35 -070045// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070046constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
47constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
48constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
49
Oskar Sundbom56ef3052018-10-30 16:11:02 +010050void UpdateEventLogStreamConfig(RtcEventLog* event_log,
51 const AudioSendStream::Config& config,
52 const AudioSendStream::Config* old_config) {
53 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
54 // Only update if any of the things we log have changed.
55 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
56 const absl::optional<SendCodecSpec>& b) {
57 if (a.has_value() && b.has_value()) {
58 return a->format.name == b->format.name &&
59 a->payload_type == b->payload_type;
60 }
61 return !a.has_value() && !b.has_value();
62 };
63
64 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
65 config.rtp.extensions == old_config->rtp.extensions &&
66 payload_types_equal(config.send_codec_spec,
67 old_config->send_codec_spec)) {
68 return;
69 }
70
Mirko Bonadei317a1f02019-09-17 17:06:18 +020071 auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
Oskar Sundbom56ef3052018-10-30 16:11:02 +010072 rtclog_config->local_ssrc = config.rtp.ssrc;
73 rtclog_config->rtp_extensions = config.rtp.extensions;
74 if (config.send_codec_spec) {
75 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
76 config.send_codec_spec->payload_type, 0);
77 }
Mirko Bonadei317a1f02019-09-17 17:06:18 +020078 event_log->Log(std::make_unique<RtcEventAudioSendStreamConfig>(
Oskar Sundbom56ef3052018-10-30 16:11:02 +010079 std::move(rtclog_config)));
80}
ossu20a4b3f2017-04-27 02:08:52 -070081} // namespace
82
Sebastian Janssonf23131f2019-10-03 10:03:55 +020083constexpr char AudioAllocationConfig::kKey[];
84
85std::unique_ptr<StructParametersParser> AudioAllocationConfig::Parser() {
86 return StructParametersParser::Create( //
87 "min", &min_bitrate, //
88 "max", &max_bitrate, //
89 "prio_rate", &priority_bitrate, //
90 "prio_rate_raw", &priority_bitrate_raw, //
91 "rate_prio", &bitrate_priority);
92}
93
94AudioAllocationConfig::AudioAllocationConfig() {
95 Parser()->Parse(field_trial::FindFullName(kKey));
96 if (priority_bitrate_raw && !priority_bitrate.IsZero()) {
97 RTC_LOG(LS_WARNING) << "'priority_bitrate' and '_raw' are mutually "
98 "exclusive but both were configured.";
99 }
100}
101
102namespace internal {
solenberg566ef242015-11-06 15:34:49 -0800103AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100104 Clock* clock,
solenberg566ef242015-11-06 15:34:49 -0800105 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100106 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100107 TaskQueueFactory* task_queue_factory,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100108 ProcessThread* module_process_thread,
Niels Möller7d76a312018-10-26 12:57:07 +0200109 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200110 BitrateAllocatorInterface* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -0800111 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -0700112 RtcpRttStats* rtcp_rtt_stats,
Sam Zackrissonff058162018-11-20 17:15:13 +0100113 const absl::optional<RtpState>& suspended_rtp_state)
Sebastian Jansson977b3352019-03-04 17:43:34 +0100114 : AudioSendStream(clock,
115 config,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100116 audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100117 task_queue_factory,
Niels Möller7d76a312018-10-26 12:57:07 +0200118 rtp_transport,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100119 bitrate_allocator,
120 event_log,
121 rtcp_rtt_stats,
122 suspended_rtp_state,
Sebastian Jansson977b3352019-03-04 17:43:34 +0100123 voe::CreateChannelSend(clock,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100124 task_queue_factory,
Niels Möllerdced9f62018-11-19 10:27:07 +0100125 module_process_thread,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700126 config.media_transport_config,
Anton Sukhanov626015d2019-02-04 15:16:06 -0800127 /*overhead_observer=*/this,
Niels Möllere9771992018-11-26 10:55:07 +0100128 config.send_transport,
Niels Möllerdced9f62018-11-19 10:27:07 +0100129 rtcp_rtt_stats,
130 event_log,
131 config.frame_encryptor,
132 config.crypto_options,
133 config.rtp.extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 15:20:15 +0200134 config.rtcp_report_interval_ms,
135 config.rtp.ssrc)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100136
137AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100138 Clock* clock,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100139 const webrtc::AudioSendStream::Config& config,
140 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100141 TaskQueueFactory* task_queue_factory,
Niels Möller7d76a312018-10-26 12:57:07 +0200142 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200143 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100144 RtcEventLog* event_log,
145 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200146 const absl::optional<RtpState>& suspended_rtp_state,
Niels Möllerdced9f62018-11-19 10:27:07 +0100147 std::unique_ptr<voe::ChannelSendInterface> channel_send)
Sebastian Jansson977b3352019-03-04 17:43:34 +0100148 : clock_(clock),
Sebastian Jansson0b698262019-03-07 09:17:19 +0100149 worker_queue_(rtp_transport->GetWorkerQueue()),
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200150 audio_send_side_bwe_(field_trial::IsEnabled("WebRTC-Audio-SendSideBwe")),
151 allocate_audio_without_feedback_(
152 field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC")),
153 enable_audio_alr_probing_(
154 !field_trial::IsDisabled("WebRTC-Audio-AlrProbing")),
155 send_side_bwe_with_overhead_(
156 field_trial::IsEnabled("WebRTC-SendSideBwe-WithOverhead")),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700157 config_(Config(/*send_transport=*/nullptr, MediaTransportConfig())),
mflodman86cc6ff2016-07-26 04:44:06 -0700158 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 10:27:07 +0100159 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 02:08:52 -0700160 event_log_(event_log),
Sebastian Jansson62aee932019-10-02 12:27:06 +0200161 use_legacy_overhead_calculation_(
162 !field_trial::IsDisabled("WebRTC-Audio-LegacyOverhead")),
michaeltf4caaab2017-01-16 23:55:07 -0800163 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 12:57:07 +0200164 rtp_transport_(rtp_transport),
elad.alond12a8e12017-03-23 11:04:48 -0700165 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
166 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700167 kRecoverablePacketLossRateMinNumAckedPairs),
168 rtp_rtcp_module_(nullptr),
Sam Zackrissonff058162018-11-20 17:15:13 +0100169 suspended_rtp_state_(suspended_rtp_state) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100170 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100171 RTC_DCHECK(worker_queue_);
172 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100173 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100174 RTC_DCHECK(bitrate_allocator_);
Sebastian Jansson0b698262019-03-07 09:17:19 +0100175 // Currently we require the rtp transport even when media transport is used.
176 RTC_DCHECK(rtp_transport);
177
Niels Möller7d76a312018-10-26 12:57:07 +0200178 // TODO(nisse): Eventually, we should have only media_transport. But for the
179 // time being, we can have either. When media transport is injected, there
180 // should be no rtp_transport, and below check should be strengthened to XOR
181 // (either rtp_transport or media_transport but not both).
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700182 RTC_DCHECK(rtp_transport || config.media_transport_config.media_transport);
183 if (config.media_transport_config.media_transport) {
Anton Sukhanov626015d2019-02-04 15:16:06 -0800184 // TODO(sukhanov): Currently media transport audio overhead is considered
185 // constant, we will not get overhead_observer calls when using
186 // media_transport. In the future when we introduce RTP media transport we
187 // should make audio overhead interface consistent and work for both RTP and
188 // non-RTP implementations.
189 audio_overhead_per_packet_bytes_ =
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700190 config.media_transport_config.media_transport->GetAudioPacketOverhead();
Anton Sukhanov626015d2019-02-04 15:16:06 -0800191 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100192 rtp_rtcp_module_ = channel_send_->GetRtpRtcp();
ossuc3d4b482017-05-23 06:07:11 -0700193 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700194
ossu20a4b3f2017-04-27 02:08:52 -0700195 ConfigureStream(this, config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700196
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200197 pacer_thread_checker_.Detach();
Niels Möller7d76a312018-10-26 12:57:07 +0200198 if (rtp_transport_) {
199 // Signal congestion controller this object is ready for OnPacket*
200 // callbacks.
201 rtp_transport_->RegisterPacketFeedbackObserver(this);
202 }
solenbergc7a8b082015-10-16 14:35:07 -0700203}
204
205AudioSendStream::~AudioSendStream() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200206 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100207 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100208 RTC_DCHECK(!sending_);
Niels Möller7d76a312018-10-26 12:57:07 +0200209 if (rtp_transport_) {
210 rtp_transport_->DeRegisterPacketFeedbackObserver(this);
Niels Möllerdced9f62018-11-19 10:27:07 +0100211 channel_send_->ResetSenderCongestionControlObjects();
Niels Möller7d76a312018-10-26 12:57:07 +0200212 }
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100213 // Blocking call to synchronize state with worker queue to ensure that there
214 // are no pending tasks left that keeps references to audio.
215 rtc::Event thread_sync_event;
216 worker_queue_->PostTask([&] { thread_sync_event.Set(); });
217 thread_sync_event.Wait(rtc::Event::kForever);
solenbergc7a8b082015-10-16 14:35:07 -0700218}
219
eladalonabbc4302017-07-26 02:09:44 -0700220const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200221 RTC_DCHECK(worker_thread_checker_.IsCurrent());
eladalonabbc4302017-07-26 02:09:44 -0700222 return config_;
223}
224
ossu20a4b3f2017-04-27 02:08:52 -0700225void AudioSendStream::Reconfigure(
226 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200227 RTC_DCHECK(worker_thread_checker_.IsCurrent());
ossu20a4b3f2017-04-27 02:08:52 -0700228 ConfigureStream(this, new_config, false);
229}
230
Alex Narestcedd3512017-12-07 20:54:55 +0100231AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
232 const std::vector<RtpExtension>& extensions) {
233 ExtensionIds ids;
234 for (const auto& extension : extensions) {
235 if (extension.uri == RtpExtension::kAudioLevelUri) {
236 ids.audio_level = extension.id;
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200237 } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
238 ids.abs_send_time = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100239 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
240 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 10:24:32 -0700241 } else if (extension.uri == RtpExtension::kMidUri) {
242 ids.mid = extension.id;
Amit Hilbuch77938e62018-12-21 09:23:38 -0800243 } else if (extension.uri == RtpExtension::kRidUri) {
244 ids.rid = extension.id;
245 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
246 ids.repaired_rid = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100247 }
248 }
249 return ids;
250}
251
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100252int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
253 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
254}
255
ossu20a4b3f2017-04-27 02:08:52 -0700256void AudioSendStream::ConfigureStream(
257 webrtc::internal::AudioSendStream* stream,
258 const webrtc::AudioSendStream::Config& new_config,
259 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100260 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
261 << new_config.ToString();
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100262 UpdateEventLogStreamConfig(stream->event_log_, new_config,
263 first_time ? nullptr : &stream->config_);
264
Niels Möllerdced9f62018-11-19 10:27:07 +0100265 const auto& channel_send = stream->channel_send_;
ossu20a4b3f2017-04-27 02:08:52 -0700266 const auto& old_config = stream->config_;
267
Yves Gerey17048012019-07-26 17:49:52 +0200268 stream->config_cs_.Enter();
269
Niels Möllere9771992018-11-26 10:55:07 +0100270 // Configuration parameters which cannot be changed.
271 RTC_DCHECK(first_time ||
272 old_config.send_transport == new_config.send_transport);
Erik Språng70efdde2019-08-21 13:36:20 +0200273 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
274 if (stream->suspended_rtp_state_ && first_time) {
Erik Språng4c2c4122019-07-11 15:20:15 +0200275 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
ossu20a4b3f2017-04-27 02:08:52 -0700276 }
277 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100278 channel_send->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700279 }
ossu20a4b3f2017-04-27 02:08:52 -0700280
Benjamin Wright84583f62018-10-04 14:22:34 -0700281 // Enable the frame encryptor if a new frame encryptor has been provided.
282 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100283 channel_send->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700284 }
285
Johannes Kron9190b822018-10-29 11:22:05 +0100286 if (first_time ||
287 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100288 channel_send->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100289 }
290
Alex Narestcedd3512017-12-07 20:54:55 +0100291 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
292 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
Yves Gerey17048012019-07-26 17:49:52 +0200293
294 stream->config_cs_.Leave();
295
ossu20a4b3f2017-04-27 02:08:52 -0700296 // Audio level indication
297 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100298 channel_send->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
299 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700300 }
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200301
302 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
303 channel_send->GetRtpRtcp()->DeregisterSendRtpHeaderExtension(
304 kRtpExtensionAbsoluteSendTime);
305 if (new_ids.abs_send_time) {
306 channel_send->GetRtpRtcp()->RegisterSendRtpHeaderExtension(
307 kRtpExtensionAbsoluteSendTime, new_ids.abs_send_time);
308 }
309 }
310
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100311 bool transport_seq_num_id_changed =
312 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100313 if (first_time || (transport_seq_num_id_changed &&
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200314 !stream->allocate_audio_without_feedback_)) {
ossu1129df22017-06-30 01:38:56 -0700315 if (!first_time) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100316 channel_send->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700317 }
318
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100319 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100320
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200321 if (stream->audio_send_side_bwe_ &&
322 !stream->allocate_audio_without_feedback_ &&
323 new_ids.transport_sequence_number != 0) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100324 channel_send->EnableSendTransportSequenceNumber(
ossu20a4b3f2017-04-27 02:08:52 -0700325 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100326 // Probing in application limited region is only used in combination with
327 // send side congestion control, wich depends on feedback packets which
328 // requires transport sequence numbers to be enabled.
Niels Möller7d76a312018-10-26 12:57:07 +0200329 if (stream->rtp_transport_) {
Christoffer Rodbroa3522482019-05-23 12:12:48 +0200330 // Optionally request ALR probing but do not override any existing
331 // request from other streams.
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200332 if (stream->enable_audio_alr_probing_) {
Christoffer Rodbroa3522482019-05-23 12:12:48 +0200333 stream->rtp_transport_->EnablePeriodicAlrProbing(true);
334 }
Niels Möller7d76a312018-10-26 12:57:07 +0200335 bandwidth_observer = stream->rtp_transport_->GetBandwidthObserver();
336 }
ossu20a4b3f2017-04-27 02:08:52 -0700337 }
Niels Möller7d76a312018-10-26 12:57:07 +0200338 if (stream->rtp_transport_) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100339 channel_send->RegisterSenderCongestionControlObjects(
Niels Möller7d76a312018-10-26 12:57:07 +0200340 stream->rtp_transport_, bandwidth_observer);
341 }
ossu20a4b3f2017-04-27 02:08:52 -0700342 }
Yves Gerey17048012019-07-26 17:49:52 +0200343 stream->config_cs_.Enter();
Steve Antonbb50ce52018-03-26 10:24:32 -0700344 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700345 if ((first_time || new_ids.mid != old_ids.mid ||
346 new_config.rtp.mid != old_config.rtp.mid) &&
347 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100348 channel_send->SetMid(new_config.rtp.mid, new_ids.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700349 }
350
Amit Hilbuch77938e62018-12-21 09:23:38 -0800351 // RID RTP header extension
352 if ((first_time || new_ids.rid != old_ids.rid ||
353 new_ids.repaired_rid != old_ids.repaired_rid ||
354 new_config.rtp.rid != old_config.rtp.rid)) {
355 channel_send->SetRid(new_config.rtp.rid, new_ids.rid, new_ids.repaired_rid);
356 }
357
ossu20a4b3f2017-04-27 02:08:52 -0700358 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700360 }
361
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100362 if (stream->sending_) {
363 ReconfigureBitrateObserver(stream, new_config);
364 }
ossu20a4b3f2017-04-27 02:08:52 -0700365 stream->config_ = new_config;
Yves Gerey17048012019-07-26 17:49:52 +0200366 stream->config_cs_.Leave();
ossu20a4b3f2017-04-27 02:08:52 -0700367}
368
solenberg3a941542015-11-16 07:34:50 -0800369void AudioSendStream::Start() {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100370 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100371 if (sending_) {
372 return;
373 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200374 // TODO(srte): We should not add audio to allocation just because
375 // audio_send_side_bwe_ is false.
376 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
377 config_.max_bitrate_bps != -1 &&
378 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0 ||
379 !audio_send_side_bwe_)) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200380 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200381 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100382 rtc::Event thread_sync_event;
383 worker_queue_->PostTask([&] {
384 RTC_DCHECK_RUN_ON(worker_queue_);
385 ConfigureBitrateObserver();
386 thread_sync_event.Set();
387 });
388 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200389 } else {
390 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700391 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100392 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100393 sending_ = true;
394 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
395 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800396}
397
398void AudioSendStream::Stop() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200399 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100400 if (!sending_) {
401 return;
402 }
403
ossu20a4b3f2017-04-27 02:08:52 -0700404 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100405 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100406 sending_ = false;
407 audio_state()->RemoveSendingStream(this);
408}
409
410void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
411 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200412 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
413 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
414 audio_frame->sample_rate_hz_;
415 {
416 // Note: SendAudioData() passes the frame further down the pipeline and it
417 // may eventually get sent. But this method is invoked even if we are not
418 // connected, as long as we have an AudioSendStream (created as a result of
419 // an O/A exchange). This means that we are calculating audio levels whether
420 // or not we are sending samples.
421 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
422 // should move from send-streams to the local audio sources or tracks; a
423 // send-stream should not be required to read the microphone audio levels.
424 rtc::CritScope cs(&audio_level_lock_);
425 audio_level_.ComputeLevel(*audio_frame, duration);
426 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100427 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800428}
429
solenbergffbbcac2016-11-17 05:25:37 -0800430bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200431 int payload_frequency,
432 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800433 int duration_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200434 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100435 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
436 payload_frequency);
437 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100438}
439
solenberg94218532016-06-16 10:53:22 -0700440void AudioSendStream::SetMuted(bool muted) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200441 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerdced9f62018-11-19 10:27:07 +0100442 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700443}
444
solenbergc7a8b082015-10-16 14:35:07 -0700445webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100446 return GetStats(true);
447}
448
449webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
450 bool has_remote_tracks) const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200451 RTC_DCHECK(worker_thread_checker_.IsCurrent());
solenberg85a04962015-10-27 03:35:21 -0700452 webrtc::AudioSendStream::Stats stats;
453 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100454 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700455
Niels Möllerdced9f62018-11-19 10:27:07 +0100456 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700457 stats.bytes_sent = call_stats.bytesSent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200458 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
solenberg85a04962015-10-27 03:35:21 -0700459 stats.packets_sent = call_stats.packetsSent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200460 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
solenberg8b85de22015-11-16 09:48:04 -0800461 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
462 // returns 0 to indicate an error value.
463 if (call_stats.rttMs > 0) {
464 stats.rtt_ms = call_stats.rttMs;
465 }
ossu20a4b3f2017-04-27 02:08:52 -0700466 if (config_.send_codec_spec) {
467 const auto& spec = *config_.send_codec_spec;
468 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100469 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700470
471 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100472 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800473 // Lookup report for send ssrc only.
474 if (block.source_SSRC == stats.local_ssrc) {
475 stats.packets_lost = block.cumulative_num_packets_lost;
476 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
ossu20a4b3f2017-04-27 02:08:52 -0700477 // Convert timestamps to milliseconds.
478 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800479 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700480 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700481 }
solenberg8b85de22015-11-16 09:48:04 -0800482 break;
solenberg85a04962015-10-27 03:35:21 -0700483 }
484 }
485 }
486
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200487 {
488 rtc::CritScope cs(&audio_level_lock_);
489 stats.audio_level = audio_level_.LevelFullRange();
490 stats.total_input_energy = audio_level_.TotalEnergy();
491 stats.total_input_duration = audio_level_.TotalDuration();
492 }
solenberg796b8f92017-03-01 17:02:23 -0800493
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100494 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100495 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100496 RTC_DCHECK(audio_state_->audio_processing());
497 stats.apm_statistics =
498 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700499
Henrik Boström6e436d12019-05-27 12:19:33 +0200500 stats.report_block_datas = std::move(call_stats.report_block_datas);
501
solenberg85a04962015-10-27 03:35:21 -0700502 return stats;
503}
504
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100505void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
pbos1ba8d392016-05-01 20:18:34 -0700506 // TODO(solenberg): Tests call this function on a network thread, libjingle
507 // calls on the worker thread. We should move towards always using a network
508 // thread. Then this check can be enabled.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200509 // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100510 channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700511}
512
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200513uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200514 RTC_DCHECK_RUN_ON(worker_queue_);
Daniel Lee93562522019-05-03 14:40:13 +0200515 // Pick a target bitrate between the constraints. Overrules the allocator if
516 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
517 // higher than max to allow for e.g. extra FEC.
518 auto constraints = GetMinMaxBitrateConstraints();
519 update.target_bitrate.Clamp(constraints.min, constraints.max);
mflodman86cc6ff2016-07-26 04:44:06 -0700520
Sebastian Jansson254d8692018-11-21 19:19:00 +0100521 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 04:44:06 -0700522
523 // The amount of audio protection is not exposed by the encoder, hence
524 // always returning 0.
525 return 0;
526}
527
elad.alond12a8e12017-03-23 11:04:48 -0700528void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200529 RTC_DCHECK(pacer_thread_checker_.IsCurrent());
elad.alond12a8e12017-03-23 11:04:48 -0700530 // Only packets that belong to this stream are of interest.
Yves Gerey17048012019-07-26 17:49:52 +0200531 bool same_ssrc;
532 {
533 rtc::CritScope lock(&config_cs_);
534 same_ssrc = ssrc == config_.rtp.ssrc;
535 }
536 if (same_ssrc) {
elad.alond12a8e12017-03-23 11:04:48 -0700537 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700538 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700539 // setting both PLR and RPLR to unknown. Consider (during upcoming
540 // refactoring) passing an indication of such an event.
Sebastian Jansson977b3352019-03-04 17:43:34 +0100541 packet_loss_tracker_.OnPacketAdded(seq_num, clock_->TimeInMilliseconds());
elad.alond12a8e12017-03-23 11:04:48 -0700542 }
543}
544
545void AudioSendStream::OnPacketFeedbackVector(
546 const std::vector<PacketFeedback>& packet_feedback_vector) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200547 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200548 absl::optional<float> plr;
549 absl::optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700550 {
551 rtc::CritScope lock(&packet_loss_tracker_cs_);
552 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
553 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700554 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700555 }
eladalonedd6eea2017-05-25 00:15:35 -0700556 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700557 // the previously sent value is no longer relevant. This will be taken care
558 // of with some refactoring which is now being done.
559 if (plr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100560 channel_send_->OnTwccBasedUplinkPacketLossRate(*plr);
elad.alond12a8e12017-03-23 11:04:48 -0700561 }
elad.alondadb4dc2017-03-23 15:29:50 -0700562 if (rplr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100563 channel_send_->OnRecoverableUplinkPacketLossRate(*rplr);
elad.alondadb4dc2017-03-23 15:29:50 -0700564 }
elad.alond12a8e12017-03-23 11:04:48 -0700565}
566
Anton Sukhanov626015d2019-02-04 15:16:06 -0800567void AudioSendStream::SetTransportOverhead(
568 int transport_overhead_per_packet_bytes) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200569 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Anton Sukhanov626015d2019-02-04 15:16:06 -0800570 rtc::CritScope cs(&overhead_per_packet_lock_);
571 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
572 UpdateOverheadForEncoder();
573}
574
575void AudioSendStream::OnOverheadChanged(
576 size_t overhead_bytes_per_packet_bytes) {
577 rtc::CritScope cs(&overhead_per_packet_lock_);
578 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
579 UpdateOverheadForEncoder();
580}
581
582void AudioSendStream::UpdateOverheadForEncoder() {
583 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700584 if (overhead_per_packet_bytes == 0) {
585 return; // Overhead is not known yet, do not tell the encoder.
586 }
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100587 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
588 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
Anton Sukhanov626015d2019-02-04 15:16:06 -0800589 });
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100590 worker_queue_->PostTask([this, overhead_per_packet_bytes] {
591 RTC_DCHECK_RUN_ON(worker_queue_);
592 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
593 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
594 if (registered_with_allocator_) {
595 ConfigureBitrateObserver();
596 }
597 }
598 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800599}
600
601size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
602 rtc::CritScope cs(&overhead_per_packet_lock_);
603 return GetPerPacketOverheadBytes();
604}
605
606size_t AudioSendStream::GetPerPacketOverheadBytes() const {
607 return transport_overhead_per_packet_bytes_ +
608 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 02:50:09 -0800609}
610
ossuc3d4b482017-05-23 06:07:11 -0700611RtpState AudioSendStream::GetRtpState() const {
612 return rtp_rtcp_module_->GetRtpState();
613}
614
Niels Möllerdced9f62018-11-19 10:27:07 +0100615const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
616 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100617}
618
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100619internal::AudioState* AudioSendStream::audio_state() {
620 internal::AudioState* audio_state =
621 static_cast<internal::AudioState*>(audio_state_.get());
622 RTC_DCHECK(audio_state);
623 return audio_state;
624}
625
626const internal::AudioState* AudioSendStream::audio_state() const {
627 internal::AudioState* audio_state =
628 static_cast<internal::AudioState*>(audio_state_.get());
629 RTC_DCHECK(audio_state);
630 return audio_state;
631}
632
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100633void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
634 size_t num_channels) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200635 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100636 encoder_sample_rate_hz_ = sample_rate_hz;
637 encoder_num_channels_ = num_channels;
638 if (sending_) {
639 // Update AudioState's information about the stream.
640 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
641 }
642}
643
minyue7a973442016-10-20 03:27:12 -0700644// Apply current codec settings to a single voe::Channel used for sending.
ossu20a4b3f2017-04-27 02:08:52 -0700645bool AudioSendStream::SetupSendCodec(AudioSendStream* stream,
646 const Config& new_config) {
647 RTC_DCHECK(new_config.send_codec_spec);
648 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700649
650 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700651 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100652 new_config.encoder_factory->MakeAudioEncoder(
653 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700654
ossu20a4b3f2017-04-27 02:08:52 -0700655 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200656 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
657 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700658 return false;
659 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200660
ossu20a4b3f2017-04-27 02:08:52 -0700661 // If a bitrate has been specified for the codec, use it over the
662 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100663 if (spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700664 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700665 }
666
ossu20a4b3f2017-04-27 02:08:52 -0700667 // Enable ANA if configured (currently only used by Opus).
668 if (new_config.audio_network_adaptor_config) {
669 if (encoder->EnableAudioNetworkAdaptor(
670 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100671 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
672 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700673 } else {
674 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700675 }
minyue7a973442016-10-20 03:27:12 -0700676 }
677
ossu20a4b3f2017-04-27 02:08:52 -0700678 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
679 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100680 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700681 cng_config.num_channels = encoder->NumChannels();
682 cng_config.payload_type = *spec.cng_payload_type;
683 cng_config.speech_encoder = std::move(encoder);
684 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100685 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700686
687 stream->RegisterCngPayloadType(
688 *spec.cng_payload_type,
689 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700690 }
ossu20a4b3f2017-04-27 02:08:52 -0700691
Anton Sukhanov626015d2019-02-04 15:16:06 -0800692 // Set currently known overhead (used in ANA, opus only).
693 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
694 {
695 rtc::CritScope cs(&stream->overhead_per_packet_lock_);
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700696 if (stream->GetPerPacketOverheadBytes() > 0) {
697 encoder->OnReceivedOverhead(stream->GetPerPacketOverheadBytes());
698 }
Anton Sukhanov626015d2019-02-04 15:16:06 -0800699 }
Sebastian Jansson62aee932019-10-02 12:27:06 +0200700 stream->worker_queue_->PostTask(
701 [stream, length_range = encoder->GetFrameLengthRange()] {
702 RTC_DCHECK_RUN_ON(stream->worker_queue_);
703 stream->frame_length_range_ = length_range;
704 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800705
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100706 stream->StoreEncoderProperties(encoder->SampleRateHz(),
707 encoder->NumChannels());
Niels Möllerdced9f62018-11-19 10:27:07 +0100708 stream->channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
709 std::move(encoder));
Anton Sukhanov626015d2019-02-04 15:16:06 -0800710
minyue7a973442016-10-20 03:27:12 -0700711 return true;
712}
713
ossu20a4b3f2017-04-27 02:08:52 -0700714bool AudioSendStream::ReconfigureSendCodec(AudioSendStream* stream,
715 const Config& new_config) {
716 const auto& old_config = stream->config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200717
718 if (!new_config.send_codec_spec) {
719 // We cannot de-configure a send codec. So we will do nothing.
720 // By design, the send codec should have not been configured.
721 RTC_DCHECK(!old_config.send_codec_spec);
722 return true;
723 }
724
725 if (new_config.send_codec_spec == old_config.send_codec_spec &&
726 new_config.audio_network_adaptor_config ==
727 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700728 return true;
729 }
730
731 // If we have no encoder, or the format or payload type's changed, create a
732 // new encoder.
733 if (!old_config.send_codec_spec ||
734 new_config.send_codec_spec->format !=
735 old_config.send_codec_spec->format ||
736 new_config.send_codec_spec->payload_type !=
737 old_config.send_codec_spec->payload_type) {
738 return SetupSendCodec(stream, new_config);
739 }
740
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200741 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700742 new_config.send_codec_spec->target_bitrate_bps;
743 // If a bitrate has been specified for the codec, use it over the
744 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100745 if (new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700746 new_target_bitrate_bps !=
747 old_config.send_codec_spec->target_bitrate_bps) {
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100748 stream->channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700749 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
750 });
751 }
752
753 ReconfigureANA(stream, new_config);
754 ReconfigureCNG(stream, new_config);
755
Anton Sukhanov626015d2019-02-04 15:16:06 -0800756 // Set currently known overhead (used in ANA, opus only).
757 {
758 rtc::CritScope cs(&stream->overhead_per_packet_lock_);
759 stream->UpdateOverheadForEncoder();
760 }
761
ossu20a4b3f2017-04-27 02:08:52 -0700762 return true;
763}
764
765void AudioSendStream::ReconfigureANA(AudioSendStream* stream,
766 const Config& new_config) {
767 if (new_config.audio_network_adaptor_config ==
768 stream->config_.audio_network_adaptor_config) {
769 return;
770 }
771 if (new_config.audio_network_adaptor_config) {
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100772 stream->channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700773 if (encoder->EnableAudioNetworkAdaptor(
774 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100775 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
776 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700777 } else {
778 RTC_NOTREACHED();
779 }
780 });
781 } else {
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100782 stream->channel_send_->CallEncoder(
783 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100784 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
785 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700786 }
787}
788
789void AudioSendStream::ReconfigureCNG(AudioSendStream* stream,
790 const Config& new_config) {
791 if (new_config.send_codec_spec->cng_payload_type ==
792 stream->config_.send_codec_spec->cng_payload_type) {
793 return;
794 }
795
ossu3b9ff382017-04-27 08:03:42 -0700796 // Register the CNG payload type if it's been added, don't do anything if CNG
797 // is removed. Payload types must not be redefined.
798 if (new_config.send_codec_spec->cng_payload_type) {
799 stream->RegisterCngPayloadType(
800 *new_config.send_codec_spec->cng_payload_type,
801 new_config.send_codec_spec->format.clockrate_hz);
802 }
803
ossu20a4b3f2017-04-27 02:08:52 -0700804 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Niels Möllerdced9f62018-11-19 10:27:07 +0100805 stream->channel_send_->ModifyEncoder(
ossu20a4b3f2017-04-27 02:08:52 -0700806 [&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
807 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
808 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
809 if (!sub_encoders.empty()) {
810 // Replace enc with its sub encoder. We need to put the sub
811 // encoder in a temporary first, since otherwise the old value
812 // of enc would be destroyed before the new value got assigned,
813 // which would be bad since the new value is a part of the old
814 // value.
815 auto tmp = std::move(sub_encoders[0]);
816 old_encoder = std::move(tmp);
817 }
818 if (new_config.send_codec_spec->cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100819 AudioEncoderCngConfig config;
ossu20a4b3f2017-04-27 02:08:52 -0700820 config.speech_encoder = std::move(old_encoder);
821 config.num_channels = config.speech_encoder->NumChannels();
822 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
823 config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100824 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
ossu20a4b3f2017-04-27 02:08:52 -0700825 } else {
826 *encoder_ptr = std::move(old_encoder);
827 }
828 });
829}
830
831void AudioSendStream::ReconfigureBitrateObserver(
832 AudioSendStream* stream,
833 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100834 RTC_DCHECK_RUN_ON(&stream->worker_thread_checker_);
ossu20a4b3f2017-04-27 02:08:52 -0700835 // Since the Config's default is for both of these to be -1, this test will
836 // allow us to configure the bitrate observer if the new config has bitrate
837 // limits set, but would only have us call RemoveBitrateObserver if we were
838 // previously configured with bitrate limits.
839 if (stream->config_.min_bitrate_bps == new_config.min_bitrate_bps &&
Alex Narestcedd3512017-12-07 20:54:55 +0100840 stream->config_.max_bitrate_bps == new_config.max_bitrate_bps &&
Seth Hampson24722b32017-12-22 09:36:42 -0800841 stream->config_.bitrate_priority == new_config.bitrate_priority &&
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100842 (TransportSeqNumId(stream->config_) == TransportSeqNumId(new_config) ||
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200843 !stream->audio_send_side_bwe_)) {
ossu20a4b3f2017-04-27 02:08:52 -0700844 return;
845 }
846
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200847 // TODO(srte): We should not add audio to allocation just because
848 // audio_send_side_bwe_ is false.
849 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
850 new_config.max_bitrate_bps != -1 &&
851 (TransportSeqNumId(new_config) != 0 || !stream->audio_send_side_bwe_)) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200852 stream->rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100853 rtc::Event thread_sync_event;
854 stream->worker_queue_->PostTask([&] {
855 RTC_DCHECK_RUN_ON(stream->worker_queue_);
856 stream->registered_with_allocator_ = true;
857 // We may get a callback immediately as the observer is registered, so
858 // make
859 // sure the bitrate limits in config_ are up-to-date.
860 stream->config_.min_bitrate_bps = new_config.min_bitrate_bps;
861 stream->config_.max_bitrate_bps = new_config.max_bitrate_bps;
862 stream->config_.bitrate_priority = new_config.bitrate_priority;
863 stream->ConfigureBitrateObserver();
864 thread_sync_event.Set();
865 });
866 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100867 stream->rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700868 } else {
Erik Språngaa59eca2019-07-24 14:52:55 +0200869 stream->rtp_transport_->AccountForAudioPacketsInPacedSender(false);
ossu20a4b3f2017-04-27 02:08:52 -0700870 stream->RemoveBitrateObserver();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200871 stream->rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700872 }
873}
874
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100875void AudioSendStream::ConfigureBitrateObserver() {
876 // This either updates the current observer or adds a new observer.
877 // TODO(srte): Add overhead compensation here.
Daniel Lee93562522019-05-03 14:40:13 +0200878 auto constraints = GetMinMaxBitrateConstraints();
879
Sebastian Jansson0429f782019-10-03 18:32:45 +0200880 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200881 if (send_side_bwe_with_overhead_) {
Sebastian Jansson0429f782019-10-03 18:32:45 +0200882 if (use_legacy_overhead_calculation_) {
883 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
884 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
885 const TimeDelta kMinPacketDuration = TimeDelta::ms(20);
886 DataRate max_overhead =
887 DataSize::bytes(kOverheadPerPacket) / kMinPacketDuration;
888 priority_bitrate += max_overhead;
889 } else {
890 RTC_DCHECK(frame_length_range_);
891 const DataSize kOverheadPerPacket =
892 DataSize::bytes(total_packet_overhead_bytes_);
893 DataRate max_overhead = kOverheadPerPacket / frame_length_range_->first;
894 priority_bitrate += max_overhead;
895 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200896 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200897 if (allocation_settings_.priority_bitrate_raw)
898 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
899
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100900 bitrate_allocator_->AddObserver(
Daniel Lee93562522019-05-03 14:40:13 +0200901 this,
902 MediaStreamAllocationConfig{
903 constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200904 priority_bitrate.bps(), true,
905 allocation_settings_.bitrate_priority.value_or(
Jonas Olsson8f119ca2019-05-08 10:56:23 +0200906 config_.bitrate_priority)});
ossu20a4b3f2017-04-27 02:08:52 -0700907}
908
909void AudioSendStream::RemoveBitrateObserver() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200910 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerc572ff32018-11-07 08:43:50 +0100911 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700912 worker_queue_->PostTask([this, &thread_sync_event] {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100913 RTC_DCHECK_RUN_ON(worker_queue_);
914 registered_with_allocator_ = false;
ossu20a4b3f2017-04-27 02:08:52 -0700915 bitrate_allocator_->RemoveObserver(this);
916 thread_sync_event.Set();
917 });
918 thread_sync_event.Wait(rtc::Event::kForever);
919}
920
Daniel Lee93562522019-05-03 14:40:13 +0200921AudioSendStream::TargetAudioBitrateConstraints
922AudioSendStream::GetMinMaxBitrateConstraints() const {
923 TargetAudioBitrateConstraints constraints{
924 DataRate::bps(config_.min_bitrate_bps),
925 DataRate::bps(config_.max_bitrate_bps)};
926
927 // If bitrates were explicitly overriden via field trial, use those values.
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200928 if (allocation_settings_.min_bitrate)
929 constraints.min = *allocation_settings_.min_bitrate;
930 if (allocation_settings_.max_bitrate)
931 constraints.max = *allocation_settings_.max_bitrate;
Daniel Lee93562522019-05-03 14:40:13 +0200932
Sebastian Jansson62aee932019-10-02 12:27:06 +0200933 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
934 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
935 RTC_DCHECK_GE(constraints.max, constraints.min);
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200936 if (send_side_bwe_with_overhead_) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200937 if (use_legacy_overhead_calculation_) {
938 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
939 const DataSize kOverheadPerPacket = DataSize::bytes(20 + 8 + 10 + 12);
940 const TimeDelta kMaxFrameLength =
941 TimeDelta::ms(60); // Based on Opus spec
942 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
943 constraints.min += kMinOverhead;
944 constraints.max += kMinOverhead;
945 } else {
946 RTC_DCHECK(frame_length_range_);
947 const DataSize kOverheadPerPacket =
948 DataSize::bytes(total_packet_overhead_bytes_);
949 constraints.min += kOverheadPerPacket / frame_length_range_->second;
950 constraints.max += kOverheadPerPacket / frame_length_range_->first;
951 }
Daniel Lee93562522019-05-03 14:40:13 +0200952 }
953 return constraints;
954}
955
ossu3b9ff382017-04-27 08:03:42 -0700956void AudioSendStream::RegisterCngPayloadType(int payload_type,
957 int clockrate_hz) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100958 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700959}
solenbergc7a8b082015-10-16 14:35:07 -0700960} // namespace internal
961} // namespace webrtc