blob: 9c709d8e9a379b9b9b1f7bb529075f78f398f90e [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "audio/audio_state.h"
Yves Gerey988cc082018-10-23 12:03:01 +020026#include "audio/channel_send.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "audio/conversion.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "call/rtp_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey988cc082018-10-23 12:03:01 +020030#include "common_audio/vad/include/vad.h"
Oskar Sundbom56ef3052018-10-30 16:11:02 +010031#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
Oskar Sundbom56ef3052018-10-30 16:11:02 +010032#include "logging/rtc_event_log/rtc_stream_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "modules/audio_processing/include/audio_processing.h"
Sebastian Jansson6298b562020-01-14 17:55:19 +010035#include "modules/rtp_rtcp/source/rtp_header_extensions.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 {
elad.alond12a8e12017-03-23 11:04:48 -070045
Oskar Sundbom56ef3052018-10-30 16:11:02 +010046void UpdateEventLogStreamConfig(RtcEventLog* event_log,
47 const AudioSendStream::Config& config,
48 const AudioSendStream::Config* old_config) {
49 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
50 // Only update if any of the things we log have changed.
51 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
52 const absl::optional<SendCodecSpec>& b) {
53 if (a.has_value() && b.has_value()) {
54 return a->format.name == b->format.name &&
55 a->payload_type == b->payload_type;
56 }
57 return !a.has_value() && !b.has_value();
58 };
59
60 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
61 config.rtp.extensions == old_config->rtp.extensions &&
62 payload_types_equal(config.send_codec_spec,
63 old_config->send_codec_spec)) {
64 return;
65 }
66
Mirko Bonadei317a1f02019-09-17 17:06:18 +020067 auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
Oskar Sundbom56ef3052018-10-30 16:11:02 +010068 rtclog_config->local_ssrc = config.rtp.ssrc;
69 rtclog_config->rtp_extensions = config.rtp.extensions;
70 if (config.send_codec_spec) {
71 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
72 config.send_codec_spec->payload_type, 0);
73 }
Mirko Bonadei317a1f02019-09-17 17:06:18 +020074 event_log->Log(std::make_unique<RtcEventAudioSendStreamConfig>(
Oskar Sundbom56ef3052018-10-30 16:11:02 +010075 std::move(rtclog_config)));
76}
ossu20a4b3f2017-04-27 02:08:52 -070077} // namespace
78
Sebastian Janssonf23131f2019-10-03 10:03:55 +020079constexpr char AudioAllocationConfig::kKey[];
80
81std::unique_ptr<StructParametersParser> AudioAllocationConfig::Parser() {
82 return StructParametersParser::Create( //
83 "min", &min_bitrate, //
84 "max", &max_bitrate, //
85 "prio_rate", &priority_bitrate, //
86 "prio_rate_raw", &priority_bitrate_raw, //
87 "rate_prio", &bitrate_priority);
88}
89
90AudioAllocationConfig::AudioAllocationConfig() {
91 Parser()->Parse(field_trial::FindFullName(kKey));
92 if (priority_bitrate_raw && !priority_bitrate.IsZero()) {
93 RTC_LOG(LS_WARNING) << "'priority_bitrate' and '_raw' are mutually "
94 "exclusive but both were configured.";
95 }
96}
97
98namespace internal {
solenberg566ef242015-11-06 15:34:49 -080099AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100100 Clock* clock,
solenberg566ef242015-11-06 15:34:49 -0800101 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100102 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100103 TaskQueueFactory* task_queue_factory,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100104 ProcessThread* module_process_thread,
Niels Möller7d76a312018-10-26 12:57:07 +0200105 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200106 BitrateAllocatorInterface* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -0800107 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -0700108 RtcpRttStats* rtcp_rtt_stats,
Sam Zackrissonff058162018-11-20 17:15:13 +0100109 const absl::optional<RtpState>& suspended_rtp_state)
Sebastian Jansson977b3352019-03-04 17:43:34 +0100110 : AudioSendStream(clock,
111 config,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100112 audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100113 task_queue_factory,
Niels Möller7d76a312018-10-26 12:57:07 +0200114 rtp_transport,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100115 bitrate_allocator,
116 event_log,
117 rtcp_rtt_stats,
118 suspended_rtp_state,
Sebastian Jansson977b3352019-03-04 17:43:34 +0100119 voe::CreateChannelSend(clock,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100120 task_queue_factory,
Niels Möllerdced9f62018-11-19 10:27:07 +0100121 module_process_thread,
Anton Sukhanov626015d2019-02-04 15:16:06 -0800122 /*overhead_observer=*/this,
Niels Möllere9771992018-11-26 10:55:07 +0100123 config.send_transport,
Niels Möllerdced9f62018-11-19 10:27:07 +0100124 rtcp_rtt_stats,
125 event_log,
126 config.frame_encryptor,
127 config.crypto_options,
128 config.rtp.extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 15:20:15 +0200129 config.rtcp_report_interval_ms,
130 config.rtp.ssrc)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100131
132AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100133 Clock* clock,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100134 const webrtc::AudioSendStream::Config& config,
135 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100136 TaskQueueFactory* task_queue_factory,
Niels Möller7d76a312018-10-26 12:57:07 +0200137 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200138 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100139 RtcEventLog* event_log,
140 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200141 const absl::optional<RtpState>& suspended_rtp_state,
Niels Möllerdced9f62018-11-19 10:27:07 +0100142 std::unique_ptr<voe::ChannelSendInterface> channel_send)
Sebastian Jansson977b3352019-03-04 17:43:34 +0100143 : clock_(clock),
Sebastian Jansson0b698262019-03-07 09:17:19 +0100144 worker_queue_(rtp_transport->GetWorkerQueue()),
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200145 audio_send_side_bwe_(field_trial::IsEnabled("WebRTC-Audio-SendSideBwe")),
146 allocate_audio_without_feedback_(
147 field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC")),
148 enable_audio_alr_probing_(
149 !field_trial::IsDisabled("WebRTC-Audio-AlrProbing")),
150 send_side_bwe_with_overhead_(
151 field_trial::IsEnabled("WebRTC-SendSideBwe-WithOverhead")),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800152 config_(Config(/*send_transport=*/nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700153 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 10:27:07 +0100154 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 02:08:52 -0700155 event_log_(event_log),
Sebastian Jansson62aee932019-10-02 12:27:06 +0200156 use_legacy_overhead_calculation_(
Sebastian Janssonbef818d2020-01-30 14:09:48 +0100157 field_trial::IsEnabled("WebRTC-Audio-LegacyOverhead")),
michaeltf4caaab2017-01-16 23:55:07 -0800158 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 12:57:07 +0200159 rtp_transport_(rtp_transport),
Sebastian Jansson6298b562020-01-14 17:55:19 +0100160 rtp_rtcp_module_(channel_send_->GetRtpRtcp()),
Sam Zackrissonff058162018-11-20 17:15:13 +0100161 suspended_rtp_state_(suspended_rtp_state) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100162 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100163 RTC_DCHECK(worker_queue_);
164 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100165 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100166 RTC_DCHECK(bitrate_allocator_);
Sebastian Jansson0b698262019-03-07 09:17:19 +0100167 RTC_DCHECK(rtp_transport);
168
ossuc3d4b482017-05-23 06:07:11 -0700169 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700170
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200171 ConfigureStream(config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700172
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200173 pacer_thread_checker_.Detach();
solenbergc7a8b082015-10-16 14:35:07 -0700174}
175
176AudioSendStream::~AudioSendStream() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200177 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100178 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100179 RTC_DCHECK(!sending_);
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200180 channel_send_->ResetSenderCongestionControlObjects();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100181 // Blocking call to synchronize state with worker queue to ensure that there
182 // are no pending tasks left that keeps references to audio.
183 rtc::Event thread_sync_event;
184 worker_queue_->PostTask([&] { thread_sync_event.Set(); });
185 thread_sync_event.Wait(rtc::Event::kForever);
solenbergc7a8b082015-10-16 14:35:07 -0700186}
187
eladalonabbc4302017-07-26 02:09:44 -0700188const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200189 RTC_DCHECK(worker_thread_checker_.IsCurrent());
eladalonabbc4302017-07-26 02:09:44 -0700190 return config_;
191}
192
ossu20a4b3f2017-04-27 02:08:52 -0700193void AudioSendStream::Reconfigure(
194 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200195 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200196 ConfigureStream(new_config, false);
ossu20a4b3f2017-04-27 02:08:52 -0700197}
198
Alex Narestcedd3512017-12-07 20:54:55 +0100199AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
200 const std::vector<RtpExtension>& extensions) {
201 ExtensionIds ids;
202 for (const auto& extension : extensions) {
203 if (extension.uri == RtpExtension::kAudioLevelUri) {
204 ids.audio_level = extension.id;
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200205 } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
206 ids.abs_send_time = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100207 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
208 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 10:24:32 -0700209 } else if (extension.uri == RtpExtension::kMidUri) {
210 ids.mid = extension.id;
Amit Hilbuch77938e62018-12-21 09:23:38 -0800211 } else if (extension.uri == RtpExtension::kRidUri) {
212 ids.rid = extension.id;
213 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
214 ids.repaired_rid = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100215 }
216 }
217 return ids;
218}
219
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100220int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
221 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
222}
223
ossu20a4b3f2017-04-27 02:08:52 -0700224void AudioSendStream::ConfigureStream(
ossu20a4b3f2017-04-27 02:08:52 -0700225 const webrtc::AudioSendStream::Config& new_config,
226 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100227 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
228 << new_config.ToString();
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200229 UpdateEventLogStreamConfig(event_log_, new_config,
230 first_time ? nullptr : &config_);
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100231
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200232 const auto& old_config = config_;
ossu20a4b3f2017-04-27 02:08:52 -0700233
Niels Möllere9771992018-11-26 10:55:07 +0100234 // Configuration parameters which cannot be changed.
235 RTC_DCHECK(first_time ||
236 old_config.send_transport == new_config.send_transport);
Erik Språng70efdde2019-08-21 13:36:20 +0200237 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200238 if (suspended_rtp_state_ && first_time) {
239 rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
ossu20a4b3f2017-04-27 02:08:52 -0700240 }
241 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200242 channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700243 }
ossu20a4b3f2017-04-27 02:08:52 -0700244
Benjamin Wright84583f62018-10-04 14:22:34 -0700245 // Enable the frame encryptor if a new frame encryptor has been provided.
246 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200247 channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700248 }
249
Johannes Kron9190b822018-10-29 11:22:05 +0100250 if (first_time ||
251 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100252 rtp_rtcp_module_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100253 }
254
Alex Narestcedd3512017-12-07 20:54:55 +0100255 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
256 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
Yves Gerey17048012019-07-26 17:49:52 +0200257
ossu20a4b3f2017-04-27 02:08:52 -0700258 // Audio level indication
259 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200260 channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
261 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700262 }
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200263
264 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100265 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200266 kRtpExtensionAbsoluteSendTime);
267 if (new_ids.abs_send_time) {
Sebastian Janssonf39c8152019-10-14 17:32:21 +0200268 rtp_rtcp_module_->RegisterRtpHeaderExtension(AbsoluteSendTime::kUri,
269 new_ids.abs_send_time);
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200270 }
271 }
272
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100273 bool transport_seq_num_id_changed =
274 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200275 if (first_time ||
276 (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
ossu1129df22017-06-30 01:38:56 -0700277 if (!first_time) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200278 channel_send_->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700279 }
280
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100281 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100282
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200283 if (audio_send_side_bwe_ && !allocate_audio_without_feedback_ &&
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200284 new_ids.transport_sequence_number != 0) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100285 rtp_rtcp_module_->RegisterRtpHeaderExtension(
286 TransportSequenceNumber::kUri, new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100287 // Probing in application limited region is only used in combination with
288 // send side congestion control, wich depends on feedback packets which
289 // requires transport sequence numbers to be enabled.
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200290 // Optionally request ALR probing but do not override any existing
291 // request from other streams.
292 if (enable_audio_alr_probing_) {
293 rtp_transport_->EnablePeriodicAlrProbing(true);
Niels Möller7d76a312018-10-26 12:57:07 +0200294 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200295 bandwidth_observer = rtp_transport_->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700296 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200297 channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
298 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700299 }
Steve Antonbb50ce52018-03-26 10:24:32 -0700300 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700301 if ((first_time || new_ids.mid != old_ids.mid ||
302 new_config.rtp.mid != old_config.rtp.mid) &&
303 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100304 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpMid::kUri, new_ids.mid);
305 rtp_rtcp_module_->SetMid(new_config.rtp.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700306 }
307
Amit Hilbuch77938e62018-12-21 09:23:38 -0800308 // RID RTP header extension
309 if ((first_time || new_ids.rid != old_ids.rid ||
310 new_ids.repaired_rid != old_ids.repaired_rid ||
311 new_config.rtp.rid != old_config.rtp.rid)) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100312 if (new_ids.rid != 0 || new_ids.repaired_rid != 0) {
313 if (new_config.rtp.rid.empty()) {
314 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(RtpStreamId::kUri);
315 } else if (new_ids.repaired_rid != 0) {
316 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
317 new_ids.repaired_rid);
318 } else {
319 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
320 new_ids.rid);
321 }
322 }
323 rtp_rtcp_module_->SetRid(new_config.rtp.rid);
Amit Hilbuch77938e62018-12-21 09:23:38 -0800324 }
325
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200326 if (!ReconfigureSendCodec(new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100327 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700328 }
329
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200330 if (sending_) {
331 ReconfigureBitrateObserver(new_config);
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100332 }
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200333 config_ = new_config;
ossu20a4b3f2017-04-27 02:08:52 -0700334}
335
solenberg3a941542015-11-16 07:34:50 -0800336void AudioSendStream::Start() {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100337 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100338 if (sending_) {
339 return;
340 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200341 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
342 config_.max_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200343 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0)) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200344 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100345 if (send_side_bwe_with_overhead_)
346 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200347 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100348 rtc::Event thread_sync_event;
349 worker_queue_->PostTask([&] {
350 RTC_DCHECK_RUN_ON(worker_queue_);
351 ConfigureBitrateObserver();
352 thread_sync_event.Set();
353 });
354 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200355 } else {
356 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700357 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100358 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100359 sending_ = true;
360 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
361 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800362}
363
364void AudioSendStream::Stop() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200365 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100366 if (!sending_) {
367 return;
368 }
369
ossu20a4b3f2017-04-27 02:08:52 -0700370 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100371 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100372 sending_ = false;
373 audio_state()->RemoveSendingStream(this);
374}
375
376void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
377 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200378 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
379 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
380 audio_frame->sample_rate_hz_;
381 {
382 // Note: SendAudioData() passes the frame further down the pipeline and it
383 // may eventually get sent. But this method is invoked even if we are not
384 // connected, as long as we have an AudioSendStream (created as a result of
385 // an O/A exchange). This means that we are calculating audio levels whether
386 // or not we are sending samples.
387 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
388 // should move from send-streams to the local audio sources or tracks; a
389 // send-stream should not be required to read the microphone audio levels.
390 rtc::CritScope cs(&audio_level_lock_);
391 audio_level_.ComputeLevel(*audio_frame, duration);
392 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100393 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800394}
395
solenbergffbbcac2016-11-17 05:25:37 -0800396bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200397 int payload_frequency,
398 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800399 int duration_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200400 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100401 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
402 payload_frequency);
403 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100404}
405
solenberg94218532016-06-16 10:53:22 -0700406void AudioSendStream::SetMuted(bool muted) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200407 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerdced9f62018-11-19 10:27:07 +0100408 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700409}
410
solenbergc7a8b082015-10-16 14:35:07 -0700411webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100412 return GetStats(true);
413}
414
415webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
416 bool has_remote_tracks) const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200417 RTC_DCHECK(worker_thread_checker_.IsCurrent());
solenberg85a04962015-10-27 03:35:21 -0700418 webrtc::AudioSendStream::Stats stats;
419 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100420 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700421
Niels Möllerdced9f62018-11-19 10:27:07 +0100422 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200423 stats.payload_bytes_sent = call_stats.payload_bytes_sent;
424 stats.header_and_padding_bytes_sent =
425 call_stats.header_and_padding_bytes_sent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200426 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
solenberg85a04962015-10-27 03:35:21 -0700427 stats.packets_sent = call_stats.packetsSent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200428 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
solenberg8b85de22015-11-16 09:48:04 -0800429 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
430 // returns 0 to indicate an error value.
431 if (call_stats.rttMs > 0) {
432 stats.rtt_ms = call_stats.rttMs;
433 }
ossu20a4b3f2017-04-27 02:08:52 -0700434 if (config_.send_codec_spec) {
435 const auto& spec = *config_.send_codec_spec;
436 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100437 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700438
439 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100440 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800441 // Lookup report for send ssrc only.
442 if (block.source_SSRC == stats.local_ssrc) {
443 stats.packets_lost = block.cumulative_num_packets_lost;
444 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
ossu20a4b3f2017-04-27 02:08:52 -0700445 // Convert timestamps to milliseconds.
446 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800447 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700448 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700449 }
solenberg8b85de22015-11-16 09:48:04 -0800450 break;
solenberg85a04962015-10-27 03:35:21 -0700451 }
452 }
453 }
454
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200455 {
456 rtc::CritScope cs(&audio_level_lock_);
457 stats.audio_level = audio_level_.LevelFullRange();
458 stats.total_input_energy = audio_level_.TotalEnergy();
459 stats.total_input_duration = audio_level_.TotalDuration();
460 }
solenberg796b8f92017-03-01 17:02:23 -0800461
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100462 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100463 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100464 RTC_DCHECK(audio_state_->audio_processing());
465 stats.apm_statistics =
466 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700467
Henrik Boström6e436d12019-05-27 12:19:33 +0200468 stats.report_block_datas = std::move(call_stats.report_block_datas);
469
solenberg85a04962015-10-27 03:35:21 -0700470 return stats;
471}
472
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100473void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
pbos1ba8d392016-05-01 20:18:34 -0700474 // TODO(solenberg): Tests call this function on a network thread, libjingle
475 // calls on the worker thread. We should move towards always using a network
476 // thread. Then this check can be enabled.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200477 // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100478 channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700479}
480
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200481uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200482 RTC_DCHECK_RUN_ON(worker_queue_);
Daniel Lee93562522019-05-03 14:40:13 +0200483 // Pick a target bitrate between the constraints. Overrules the allocator if
484 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
485 // higher than max to allow for e.g. extra FEC.
486 auto constraints = GetMinMaxBitrateConstraints();
487 update.target_bitrate.Clamp(constraints.min, constraints.max);
mflodman86cc6ff2016-07-26 04:44:06 -0700488
Sebastian Jansson254d8692018-11-21 19:19:00 +0100489 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 04:44:06 -0700490
491 // The amount of audio protection is not exposed by the encoder, hence
492 // always returning 0.
493 return 0;
494}
495
Anton Sukhanov626015d2019-02-04 15:16:06 -0800496void AudioSendStream::SetTransportOverhead(
497 int transport_overhead_per_packet_bytes) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200498 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Anton Sukhanov626015d2019-02-04 15:16:06 -0800499 rtc::CritScope cs(&overhead_per_packet_lock_);
500 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
501 UpdateOverheadForEncoder();
502}
503
504void AudioSendStream::OnOverheadChanged(
505 size_t overhead_bytes_per_packet_bytes) {
506 rtc::CritScope cs(&overhead_per_packet_lock_);
507 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
508 UpdateOverheadForEncoder();
509}
510
511void AudioSendStream::UpdateOverheadForEncoder() {
512 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700513 if (overhead_per_packet_bytes == 0) {
514 return; // Overhead is not known yet, do not tell the encoder.
515 }
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100516 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
517 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
Anton Sukhanov626015d2019-02-04 15:16:06 -0800518 });
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100519 worker_queue_->PostTask([this, overhead_per_packet_bytes] {
520 RTC_DCHECK_RUN_ON(worker_queue_);
521 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
522 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
523 if (registered_with_allocator_) {
524 ConfigureBitrateObserver();
525 }
526 }
527 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800528}
529
530size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
531 rtc::CritScope cs(&overhead_per_packet_lock_);
532 return GetPerPacketOverheadBytes();
533}
534
535size_t AudioSendStream::GetPerPacketOverheadBytes() const {
536 return transport_overhead_per_packet_bytes_ +
537 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 02:50:09 -0800538}
539
ossuc3d4b482017-05-23 06:07:11 -0700540RtpState AudioSendStream::GetRtpState() const {
541 return rtp_rtcp_module_->GetRtpState();
542}
543
Niels Möllerdced9f62018-11-19 10:27:07 +0100544const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
545 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100546}
547
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100548internal::AudioState* AudioSendStream::audio_state() {
549 internal::AudioState* audio_state =
550 static_cast<internal::AudioState*>(audio_state_.get());
551 RTC_DCHECK(audio_state);
552 return audio_state;
553}
554
555const internal::AudioState* AudioSendStream::audio_state() const {
556 internal::AudioState* audio_state =
557 static_cast<internal::AudioState*>(audio_state_.get());
558 RTC_DCHECK(audio_state);
559 return audio_state;
560}
561
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100562void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
563 size_t num_channels) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200564 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100565 encoder_sample_rate_hz_ = sample_rate_hz;
566 encoder_num_channels_ = num_channels;
567 if (sending_) {
568 // Update AudioState's information about the stream.
569 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
570 }
571}
572
minyue7a973442016-10-20 03:27:12 -0700573// Apply current codec settings to a single voe::Channel used for sending.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200574bool AudioSendStream::SetupSendCodec(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700575 RTC_DCHECK(new_config.send_codec_spec);
576 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700577
578 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700579 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100580 new_config.encoder_factory->MakeAudioEncoder(
581 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700582
ossu20a4b3f2017-04-27 02:08:52 -0700583 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200584 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
585 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700586 return false;
587 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200588
ossu20a4b3f2017-04-27 02:08:52 -0700589 // If a bitrate has been specified for the codec, use it over the
590 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100591 if (spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700592 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700593 }
594
ossu20a4b3f2017-04-27 02:08:52 -0700595 // Enable ANA if configured (currently only used by Opus).
Mirko Bonadei43564902020-01-29 15:29:36 +0000596 if (new_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700597 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200598 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100599 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
600 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700601 } else {
602 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700603 }
minyue7a973442016-10-20 03:27:12 -0700604 }
605
ossu20a4b3f2017-04-27 02:08:52 -0700606 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
607 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100608 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700609 cng_config.num_channels = encoder->NumChannels();
610 cng_config.payload_type = *spec.cng_payload_type;
611 cng_config.speech_encoder = std::move(encoder);
612 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100613 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700614
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200615 RegisterCngPayloadType(*spec.cng_payload_type,
616 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700617 }
ossu20a4b3f2017-04-27 02:08:52 -0700618
Anton Sukhanov626015d2019-02-04 15:16:06 -0800619 // Set currently known overhead (used in ANA, opus only).
620 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
621 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200622 rtc::CritScope cs(&overhead_per_packet_lock_);
623 if (GetPerPacketOverheadBytes() > 0) {
624 encoder->OnReceivedOverhead(GetPerPacketOverheadBytes());
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700625 }
Anton Sukhanov626015d2019-02-04 15:16:06 -0800626 }
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200627 worker_queue_->PostTask(
628 [this, length_range = encoder->GetFrameLengthRange()] {
629 RTC_DCHECK_RUN_ON(worker_queue_);
630 frame_length_range_ = length_range;
Sebastian Jansson62aee932019-10-02 12:27:06 +0200631 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800632
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200633 StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
634 channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
635 std::move(encoder));
Anton Sukhanov626015d2019-02-04 15:16:06 -0800636
minyue7a973442016-10-20 03:27:12 -0700637 return true;
638}
639
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200640bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
641 const auto& old_config = config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200642
643 if (!new_config.send_codec_spec) {
644 // We cannot de-configure a send codec. So we will do nothing.
645 // By design, the send codec should have not been configured.
646 RTC_DCHECK(!old_config.send_codec_spec);
647 return true;
648 }
649
650 if (new_config.send_codec_spec == old_config.send_codec_spec &&
651 new_config.audio_network_adaptor_config ==
652 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700653 return true;
654 }
655
656 // If we have no encoder, or the format or payload type's changed, create a
657 // new encoder.
658 if (!old_config.send_codec_spec ||
659 new_config.send_codec_spec->format !=
660 old_config.send_codec_spec->format ||
661 new_config.send_codec_spec->payload_type !=
662 old_config.send_codec_spec->payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200663 return SetupSendCodec(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700664 }
665
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200666 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700667 new_config.send_codec_spec->target_bitrate_bps;
668 // If a bitrate has been specified for the codec, use it over the
669 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100670 if (new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700671 new_target_bitrate_bps !=
672 old_config.send_codec_spec->target_bitrate_bps) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200673 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700674 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
675 });
676 }
677
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200678 ReconfigureANA(new_config);
679 ReconfigureCNG(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700680
Anton Sukhanov626015d2019-02-04 15:16:06 -0800681 // Set currently known overhead (used in ANA, opus only).
682 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200683 rtc::CritScope cs(&overhead_per_packet_lock_);
684 UpdateOverheadForEncoder();
Anton Sukhanov626015d2019-02-04 15:16:06 -0800685 }
686
ossu20a4b3f2017-04-27 02:08:52 -0700687 return true;
688}
689
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200690void AudioSendStream::ReconfigureANA(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700691 if (new_config.audio_network_adaptor_config ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200692 config_.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700693 return;
694 }
Mirko Bonadei43564902020-01-29 15:29:36 +0000695 if (new_config.audio_network_adaptor_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200696 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700697 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200698 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100699 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
700 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700701 } else {
702 RTC_NOTREACHED();
703 }
704 });
705 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200706 channel_send_->CallEncoder(
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100707 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100708 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
709 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700710 }
711}
712
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200713void AudioSendStream::ReconfigureCNG(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700714 if (new_config.send_codec_spec->cng_payload_type ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200715 config_.send_codec_spec->cng_payload_type) {
ossu20a4b3f2017-04-27 02:08:52 -0700716 return;
717 }
718
ossu3b9ff382017-04-27 08:03:42 -0700719 // Register the CNG payload type if it's been added, don't do anything if CNG
720 // is removed. Payload types must not be redefined.
721 if (new_config.send_codec_spec->cng_payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200722 RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
723 new_config.send_codec_spec->format.clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700724 }
725
ossu20a4b3f2017-04-27 02:08:52 -0700726 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200727 channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
728 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
729 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
730 if (!sub_encoders.empty()) {
731 // Replace enc with its sub encoder. We need to put the sub
732 // encoder in a temporary first, since otherwise the old value
733 // of enc would be destroyed before the new value got assigned,
734 // which would be bad since the new value is a part of the old
735 // value.
736 auto tmp = std::move(sub_encoders[0]);
737 old_encoder = std::move(tmp);
738 }
739 if (new_config.send_codec_spec->cng_payload_type) {
740 AudioEncoderCngConfig config;
741 config.speech_encoder = std::move(old_encoder);
742 config.num_channels = config.speech_encoder->NumChannels();
743 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
744 config.vad_mode = Vad::kVadNormal;
745 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
746 } else {
747 *encoder_ptr = std::move(old_encoder);
748 }
749 });
ossu20a4b3f2017-04-27 02:08:52 -0700750}
751
752void AudioSendStream::ReconfigureBitrateObserver(
ossu20a4b3f2017-04-27 02:08:52 -0700753 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200754 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
ossu20a4b3f2017-04-27 02:08:52 -0700755 // Since the Config's default is for both of these to be -1, this test will
756 // allow us to configure the bitrate observer if the new config has bitrate
757 // limits set, but would only have us call RemoveBitrateObserver if we were
758 // previously configured with bitrate limits.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200759 if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
760 config_.max_bitrate_bps == new_config.max_bitrate_bps &&
761 config_.bitrate_priority == new_config.bitrate_priority &&
762 (TransportSeqNumId(config_) == TransportSeqNumId(new_config) ||
763 !audio_send_side_bwe_)) {
ossu20a4b3f2017-04-27 02:08:52 -0700764 return;
765 }
766
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200767 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200768 new_config.max_bitrate_bps != -1 && TransportSeqNumId(new_config) != 0) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200769 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100770 if (send_side_bwe_with_overhead_)
771 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100772 rtc::Event thread_sync_event;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200773 worker_queue_->PostTask([&] {
774 RTC_DCHECK_RUN_ON(worker_queue_);
775 registered_with_allocator_ = true;
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100776 // We may get a callback immediately as the observer is registered, so
777 // make
778 // sure the bitrate limits in config_ are up-to-date.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200779 config_.min_bitrate_bps = new_config.min_bitrate_bps;
780 config_.max_bitrate_bps = new_config.max_bitrate_bps;
781
782 config_.bitrate_priority = new_config.bitrate_priority;
783 ConfigureBitrateObserver();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100784 thread_sync_event.Set();
785 });
786 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200787 rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700788 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200789 rtp_transport_->AccountForAudioPacketsInPacedSender(false);
790 RemoveBitrateObserver();
791 rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700792 }
793}
794
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100795void AudioSendStream::ConfigureBitrateObserver() {
796 // This either updates the current observer or adds a new observer.
797 // TODO(srte): Add overhead compensation here.
Daniel Lee93562522019-05-03 14:40:13 +0200798 auto constraints = GetMinMaxBitrateConstraints();
799
Sebastian Jansson0429f782019-10-03 18:32:45 +0200800 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200801 if (send_side_bwe_with_overhead_) {
Sebastian Jansson0429f782019-10-03 18:32:45 +0200802 if (use_legacy_overhead_calculation_) {
803 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
804 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100805 const TimeDelta kMinPacketDuration = TimeDelta::Millis(20);
Sebastian Jansson0429f782019-10-03 18:32:45 +0200806 DataRate max_overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100807 DataSize::Bytes(kOverheadPerPacket) / kMinPacketDuration;
Sebastian Jansson0429f782019-10-03 18:32:45 +0200808 priority_bitrate += max_overhead;
809 } else {
810 RTC_DCHECK(frame_length_range_);
811 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100812 DataSize::Bytes(total_packet_overhead_bytes_);
Sebastian Jansson0429f782019-10-03 18:32:45 +0200813 DataRate max_overhead = kOverheadPerPacket / frame_length_range_->first;
814 priority_bitrate += max_overhead;
815 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200816 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200817 if (allocation_settings_.priority_bitrate_raw)
818 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
819
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100820 bitrate_allocator_->AddObserver(
Daniel Lee93562522019-05-03 14:40:13 +0200821 this,
822 MediaStreamAllocationConfig{
823 constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200824 priority_bitrate.bps(), true,
825 allocation_settings_.bitrate_priority.value_or(
Jonas Olsson8f119ca2019-05-08 10:56:23 +0200826 config_.bitrate_priority)});
ossu20a4b3f2017-04-27 02:08:52 -0700827}
828
829void AudioSendStream::RemoveBitrateObserver() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200830 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerc572ff32018-11-07 08:43:50 +0100831 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700832 worker_queue_->PostTask([this, &thread_sync_event] {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100833 RTC_DCHECK_RUN_ON(worker_queue_);
834 registered_with_allocator_ = false;
ossu20a4b3f2017-04-27 02:08:52 -0700835 bitrate_allocator_->RemoveObserver(this);
836 thread_sync_event.Set();
837 });
838 thread_sync_event.Wait(rtc::Event::kForever);
839}
840
Daniel Lee93562522019-05-03 14:40:13 +0200841AudioSendStream::TargetAudioBitrateConstraints
842AudioSendStream::GetMinMaxBitrateConstraints() const {
843 TargetAudioBitrateConstraints constraints{
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100844 DataRate::BitsPerSec(config_.min_bitrate_bps),
845 DataRate::BitsPerSec(config_.max_bitrate_bps)};
Daniel Lee93562522019-05-03 14:40:13 +0200846
847 // If bitrates were explicitly overriden via field trial, use those values.
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200848 if (allocation_settings_.min_bitrate)
849 constraints.min = *allocation_settings_.min_bitrate;
850 if (allocation_settings_.max_bitrate)
851 constraints.max = *allocation_settings_.max_bitrate;
Daniel Lee93562522019-05-03 14:40:13 +0200852
Sebastian Jansson62aee932019-10-02 12:27:06 +0200853 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
854 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
855 RTC_DCHECK_GE(constraints.max, constraints.min);
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200856 if (send_side_bwe_with_overhead_) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200857 if (use_legacy_overhead_calculation_) {
858 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100859 const DataSize kOverheadPerPacket = DataSize::Bytes(20 + 8 + 10 + 12);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200860 const TimeDelta kMaxFrameLength =
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100861 TimeDelta::Millis(60); // Based on Opus spec
Sebastian Jansson62aee932019-10-02 12:27:06 +0200862 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
863 constraints.min += kMinOverhead;
864 constraints.max += kMinOverhead;
865 } else {
866 RTC_DCHECK(frame_length_range_);
867 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100868 DataSize::Bytes(total_packet_overhead_bytes_);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200869 constraints.min += kOverheadPerPacket / frame_length_range_->second;
870 constraints.max += kOverheadPerPacket / frame_length_range_->first;
871 }
Daniel Lee93562522019-05-03 14:40:13 +0200872 }
873 return constraints;
874}
875
ossu3b9ff382017-04-27 08:03:42 -0700876void AudioSendStream::RegisterCngPayloadType(int payload_type,
877 int clockrate_hz) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100878 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700879}
solenbergc7a8b082015-10-16 14:35:07 -0700880} // namespace internal
881} // namespace webrtc