blob: 2dcb37adf12eb96c2269752d308a83eee69b1310 [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;
Minyue Li74dadc12020-03-05 11:33:13 +0100215 } else if (extension.uri == RtpExtension::kAbsoluteCaptureTimeUri) {
216 ids.abs_capture_time = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100217 }
218 }
219 return ids;
220}
221
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100222int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
223 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
224}
225
ossu20a4b3f2017-04-27 02:08:52 -0700226void AudioSendStream::ConfigureStream(
ossu20a4b3f2017-04-27 02:08:52 -0700227 const webrtc::AudioSendStream::Config& new_config,
228 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100229 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
230 << new_config.ToString();
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200231 UpdateEventLogStreamConfig(event_log_, new_config,
232 first_time ? nullptr : &config_);
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100233
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200234 const auto& old_config = config_;
ossu20a4b3f2017-04-27 02:08:52 -0700235
Niels Möllere9771992018-11-26 10:55:07 +0100236 // Configuration parameters which cannot be changed.
237 RTC_DCHECK(first_time ||
238 old_config.send_transport == new_config.send_transport);
Erik Språng70efdde2019-08-21 13:36:20 +0200239 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200240 if (suspended_rtp_state_ && first_time) {
241 rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
ossu20a4b3f2017-04-27 02:08:52 -0700242 }
243 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200244 channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700245 }
ossu20a4b3f2017-04-27 02:08:52 -0700246
Benjamin Wright84583f62018-10-04 14:22:34 -0700247 // Enable the frame encryptor if a new frame encryptor has been provided.
248 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200249 channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700250 }
251
Johannes Kron9190b822018-10-29 11:22:05 +0100252 if (first_time ||
253 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100254 rtp_rtcp_module_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100255 }
256
Alex Narestcedd3512017-12-07 20:54:55 +0100257 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
258 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
Yves Gerey17048012019-07-26 17:49:52 +0200259
ossu20a4b3f2017-04-27 02:08:52 -0700260 // Audio level indication
261 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200262 channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
263 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700264 }
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200265
266 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100267 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200268 kRtpExtensionAbsoluteSendTime);
269 if (new_ids.abs_send_time) {
Sebastian Janssonf39c8152019-10-14 17:32:21 +0200270 rtp_rtcp_module_->RegisterRtpHeaderExtension(AbsoluteSendTime::kUri,
271 new_ids.abs_send_time);
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200272 }
273 }
274
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100275 bool transport_seq_num_id_changed =
276 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200277 if (first_time ||
278 (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
ossu1129df22017-06-30 01:38:56 -0700279 if (!first_time) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200280 channel_send_->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700281 }
282
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100283 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100284
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200285 if (audio_send_side_bwe_ && !allocate_audio_without_feedback_ &&
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200286 new_ids.transport_sequence_number != 0) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100287 rtp_rtcp_module_->RegisterRtpHeaderExtension(
288 TransportSequenceNumber::kUri, new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100289 // Probing in application limited region is only used in combination with
290 // send side congestion control, wich depends on feedback packets which
291 // requires transport sequence numbers to be enabled.
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200292 // Optionally request ALR probing but do not override any existing
293 // request from other streams.
294 if (enable_audio_alr_probing_) {
295 rtp_transport_->EnablePeriodicAlrProbing(true);
Niels Möller7d76a312018-10-26 12:57:07 +0200296 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200297 bandwidth_observer = rtp_transport_->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700298 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200299 channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
300 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700301 }
Steve Antonbb50ce52018-03-26 10:24:32 -0700302 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700303 if ((first_time || new_ids.mid != old_ids.mid ||
304 new_config.rtp.mid != old_config.rtp.mid) &&
305 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100306 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpMid::kUri, new_ids.mid);
307 rtp_rtcp_module_->SetMid(new_config.rtp.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700308 }
309
Amit Hilbuch77938e62018-12-21 09:23:38 -0800310 // RID RTP header extension
311 if ((first_time || new_ids.rid != old_ids.rid ||
312 new_ids.repaired_rid != old_ids.repaired_rid ||
313 new_config.rtp.rid != old_config.rtp.rid)) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100314 if (new_ids.rid != 0 || new_ids.repaired_rid != 0) {
315 if (new_config.rtp.rid.empty()) {
316 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(RtpStreamId::kUri);
317 } else if (new_ids.repaired_rid != 0) {
318 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
319 new_ids.repaired_rid);
320 } else {
321 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
322 new_ids.rid);
323 }
324 }
325 rtp_rtcp_module_->SetRid(new_config.rtp.rid);
Amit Hilbuch77938e62018-12-21 09:23:38 -0800326 }
327
Minyue Li74dadc12020-03-05 11:33:13 +0100328 if (first_time || new_ids.abs_capture_time != old_ids.abs_capture_time) {
329 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(
330 kRtpExtensionAbsoluteCaptureTime);
331 if (new_ids.abs_capture_time) {
332 rtp_rtcp_module_->RegisterRtpHeaderExtension(
333 AbsoluteCaptureTimeExtension::kUri, new_ids.abs_capture_time);
334 }
335 }
336
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200337 if (!ReconfigureSendCodec(new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100338 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700339 }
340
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100341 channel_send_->CallEncoder([this](AudioEncoder* encoder) {
342 if (!encoder) {
343 return;
344 }
345 worker_queue_->PostTask(
346 [this, length_range = encoder->GetFrameLengthRange()] {
347 RTC_DCHECK_RUN_ON(worker_queue_);
348 frame_length_range_ = length_range;
349 });
350 });
351
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200352 if (sending_) {
353 ReconfigureBitrateObserver(new_config);
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100354 }
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200355 config_ = new_config;
ossu20a4b3f2017-04-27 02:08:52 -0700356}
357
solenberg3a941542015-11-16 07:34:50 -0800358void AudioSendStream::Start() {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100359 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100360 if (sending_) {
361 return;
362 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200363 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
364 config_.max_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200365 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0)) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200366 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100367 if (send_side_bwe_with_overhead_)
368 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200369 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100370 rtc::Event thread_sync_event;
371 worker_queue_->PostTask([&] {
372 RTC_DCHECK_RUN_ON(worker_queue_);
373 ConfigureBitrateObserver();
374 thread_sync_event.Set();
375 });
376 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200377 } else {
378 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700379 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100380 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100381 sending_ = true;
382 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
383 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800384}
385
386void AudioSendStream::Stop() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200387 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100388 if (!sending_) {
389 return;
390 }
391
ossu20a4b3f2017-04-27 02:08:52 -0700392 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100393 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100394 sending_ = false;
395 audio_state()->RemoveSendingStream(this);
396}
397
398void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
399 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200400 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
401 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
402 audio_frame->sample_rate_hz_;
403 {
404 // Note: SendAudioData() passes the frame further down the pipeline and it
405 // may eventually get sent. But this method is invoked even if we are not
406 // connected, as long as we have an AudioSendStream (created as a result of
407 // an O/A exchange). This means that we are calculating audio levels whether
408 // or not we are sending samples.
409 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
410 // should move from send-streams to the local audio sources or tracks; a
411 // send-stream should not be required to read the microphone audio levels.
412 rtc::CritScope cs(&audio_level_lock_);
413 audio_level_.ComputeLevel(*audio_frame, duration);
414 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100415 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800416}
417
solenbergffbbcac2016-11-17 05:25:37 -0800418bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200419 int payload_frequency,
420 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800421 int duration_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200422 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100423 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
424 payload_frequency);
425 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100426}
427
solenberg94218532016-06-16 10:53:22 -0700428void AudioSendStream::SetMuted(bool muted) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200429 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerdced9f62018-11-19 10:27:07 +0100430 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700431}
432
solenbergc7a8b082015-10-16 14:35:07 -0700433webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100434 return GetStats(true);
435}
436
437webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
438 bool has_remote_tracks) const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200439 RTC_DCHECK(worker_thread_checker_.IsCurrent());
solenberg85a04962015-10-27 03:35:21 -0700440 webrtc::AudioSendStream::Stats stats;
441 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100442 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700443
Niels Möllerdced9f62018-11-19 10:27:07 +0100444 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200445 stats.payload_bytes_sent = call_stats.payload_bytes_sent;
446 stats.header_and_padding_bytes_sent =
447 call_stats.header_and_padding_bytes_sent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200448 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
solenberg85a04962015-10-27 03:35:21 -0700449 stats.packets_sent = call_stats.packetsSent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200450 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
solenberg8b85de22015-11-16 09:48:04 -0800451 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
452 // returns 0 to indicate an error value.
453 if (call_stats.rttMs > 0) {
454 stats.rtt_ms = call_stats.rttMs;
455 }
ossu20a4b3f2017-04-27 02:08:52 -0700456 if (config_.send_codec_spec) {
457 const auto& spec = *config_.send_codec_spec;
458 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100459 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700460
461 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100462 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800463 // Lookup report for send ssrc only.
464 if (block.source_SSRC == stats.local_ssrc) {
465 stats.packets_lost = block.cumulative_num_packets_lost;
466 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
ossu20a4b3f2017-04-27 02:08:52 -0700467 // Convert timestamps to milliseconds.
468 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800469 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700470 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700471 }
solenberg8b85de22015-11-16 09:48:04 -0800472 break;
solenberg85a04962015-10-27 03:35:21 -0700473 }
474 }
475 }
476
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200477 {
478 rtc::CritScope cs(&audio_level_lock_);
479 stats.audio_level = audio_level_.LevelFullRange();
480 stats.total_input_energy = audio_level_.TotalEnergy();
481 stats.total_input_duration = audio_level_.TotalDuration();
482 }
solenberg796b8f92017-03-01 17:02:23 -0800483
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100484 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100485 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100486 RTC_DCHECK(audio_state_->audio_processing());
487 stats.apm_statistics =
488 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700489
Henrik Boström6e436d12019-05-27 12:19:33 +0200490 stats.report_block_datas = std::move(call_stats.report_block_datas);
491
solenberg85a04962015-10-27 03:35:21 -0700492 return stats;
493}
494
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100495void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
pbos1ba8d392016-05-01 20:18:34 -0700496 // TODO(solenberg): Tests call this function on a network thread, libjingle
497 // calls on the worker thread. We should move towards always using a network
498 // thread. Then this check can be enabled.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200499 // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100500 channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700501}
502
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200503uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200504 RTC_DCHECK_RUN_ON(worker_queue_);
Daniel Lee93562522019-05-03 14:40:13 +0200505 // Pick a target bitrate between the constraints. Overrules the allocator if
506 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
507 // higher than max to allow for e.g. extra FEC.
508 auto constraints = GetMinMaxBitrateConstraints();
509 update.target_bitrate.Clamp(constraints.min, constraints.max);
Jakob Ivarsson0c964492020-03-11 09:18:59 +0100510 update.stable_target_bitrate.Clamp(constraints.min, constraints.max);
mflodman86cc6ff2016-07-26 04:44:06 -0700511
Sebastian Jansson254d8692018-11-21 19:19:00 +0100512 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 04:44:06 -0700513
514 // The amount of audio protection is not exposed by the encoder, hence
515 // always returning 0.
516 return 0;
517}
518
Anton Sukhanov626015d2019-02-04 15:16:06 -0800519void AudioSendStream::SetTransportOverhead(
520 int transport_overhead_per_packet_bytes) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200521 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Anton Sukhanov626015d2019-02-04 15:16:06 -0800522 rtc::CritScope cs(&overhead_per_packet_lock_);
523 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
524 UpdateOverheadForEncoder();
525}
526
527void AudioSendStream::OnOverheadChanged(
528 size_t overhead_bytes_per_packet_bytes) {
529 rtc::CritScope cs(&overhead_per_packet_lock_);
530 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
531 UpdateOverheadForEncoder();
532}
533
534void AudioSendStream::UpdateOverheadForEncoder() {
535 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700536 if (overhead_per_packet_bytes == 0) {
537 return; // Overhead is not known yet, do not tell the encoder.
538 }
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100539 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
540 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
Anton Sukhanov626015d2019-02-04 15:16:06 -0800541 });
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100542 worker_queue_->PostTask([this, overhead_per_packet_bytes] {
543 RTC_DCHECK_RUN_ON(worker_queue_);
544 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
545 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
546 if (registered_with_allocator_) {
547 ConfigureBitrateObserver();
548 }
549 }
550 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800551}
552
553size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
554 rtc::CritScope cs(&overhead_per_packet_lock_);
555 return GetPerPacketOverheadBytes();
556}
557
558size_t AudioSendStream::GetPerPacketOverheadBytes() const {
559 return transport_overhead_per_packet_bytes_ +
560 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 02:50:09 -0800561}
562
ossuc3d4b482017-05-23 06:07:11 -0700563RtpState AudioSendStream::GetRtpState() const {
564 return rtp_rtcp_module_->GetRtpState();
565}
566
Niels Möllerdced9f62018-11-19 10:27:07 +0100567const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
568 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100569}
570
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100571internal::AudioState* AudioSendStream::audio_state() {
572 internal::AudioState* audio_state =
573 static_cast<internal::AudioState*>(audio_state_.get());
574 RTC_DCHECK(audio_state);
575 return audio_state;
576}
577
578const internal::AudioState* AudioSendStream::audio_state() const {
579 internal::AudioState* audio_state =
580 static_cast<internal::AudioState*>(audio_state_.get());
581 RTC_DCHECK(audio_state);
582 return audio_state;
583}
584
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100585void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
586 size_t num_channels) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200587 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100588 encoder_sample_rate_hz_ = sample_rate_hz;
589 encoder_num_channels_ = num_channels;
590 if (sending_) {
591 // Update AudioState's information about the stream.
592 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
593 }
594}
595
minyue7a973442016-10-20 03:27:12 -0700596// Apply current codec settings to a single voe::Channel used for sending.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200597bool AudioSendStream::SetupSendCodec(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700598 RTC_DCHECK(new_config.send_codec_spec);
599 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700600
601 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700602 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100603 new_config.encoder_factory->MakeAudioEncoder(
604 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700605
ossu20a4b3f2017-04-27 02:08:52 -0700606 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200607 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
608 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700609 return false;
610 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200611
ossu20a4b3f2017-04-27 02:08:52 -0700612 // If a bitrate has been specified for the codec, use it over the
613 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100614 if (spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700615 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700616 }
617
ossu20a4b3f2017-04-27 02:08:52 -0700618 // Enable ANA if configured (currently only used by Opus).
Mirko Bonadei43564902020-01-29 15:29:36 +0000619 if (new_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700620 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200621 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100622 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
623 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700624 } else {
Alejandro Luebsc7710842020-03-05 12:05:50 -0800625 RTC_DLOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
626 << new_config.rtp.ssrc;
minyue6b825df2016-10-31 04:08:32 -0700627 }
minyue7a973442016-10-20 03:27:12 -0700628 }
629
ossu20a4b3f2017-04-27 02:08:52 -0700630 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
631 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100632 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700633 cng_config.num_channels = encoder->NumChannels();
634 cng_config.payload_type = *spec.cng_payload_type;
635 cng_config.speech_encoder = std::move(encoder);
636 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100637 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700638
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200639 RegisterCngPayloadType(*spec.cng_payload_type,
640 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700641 }
ossu20a4b3f2017-04-27 02:08:52 -0700642
Anton Sukhanov626015d2019-02-04 15:16:06 -0800643 // Set currently known overhead (used in ANA, opus only).
644 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
645 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200646 rtc::CritScope cs(&overhead_per_packet_lock_);
647 if (GetPerPacketOverheadBytes() > 0) {
648 encoder->OnReceivedOverhead(GetPerPacketOverheadBytes());
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700649 }
Anton Sukhanov626015d2019-02-04 15:16:06 -0800650 }
651
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200652 StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
653 channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
654 std::move(encoder));
Anton Sukhanov626015d2019-02-04 15:16:06 -0800655
minyue7a973442016-10-20 03:27:12 -0700656 return true;
657}
658
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200659bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
660 const auto& old_config = config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200661
662 if (!new_config.send_codec_spec) {
663 // We cannot de-configure a send codec. So we will do nothing.
664 // By design, the send codec should have not been configured.
665 RTC_DCHECK(!old_config.send_codec_spec);
666 return true;
667 }
668
669 if (new_config.send_codec_spec == old_config.send_codec_spec &&
670 new_config.audio_network_adaptor_config ==
671 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700672 return true;
673 }
674
675 // If we have no encoder, or the format or payload type's changed, create a
676 // new encoder.
677 if (!old_config.send_codec_spec ||
678 new_config.send_codec_spec->format !=
679 old_config.send_codec_spec->format ||
680 new_config.send_codec_spec->payload_type !=
681 old_config.send_codec_spec->payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200682 return SetupSendCodec(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700683 }
684
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200685 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700686 new_config.send_codec_spec->target_bitrate_bps;
687 // If a bitrate has been specified for the codec, use it over the
688 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100689 if (new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700690 new_target_bitrate_bps !=
691 old_config.send_codec_spec->target_bitrate_bps) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200692 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700693 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
694 });
695 }
696
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200697 ReconfigureANA(new_config);
698 ReconfigureCNG(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700699
Anton Sukhanov626015d2019-02-04 15:16:06 -0800700 // Set currently known overhead (used in ANA, opus only).
701 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200702 rtc::CritScope cs(&overhead_per_packet_lock_);
703 UpdateOverheadForEncoder();
Anton Sukhanov626015d2019-02-04 15:16:06 -0800704 }
705
ossu20a4b3f2017-04-27 02:08:52 -0700706 return true;
707}
708
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200709void AudioSendStream::ReconfigureANA(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700710 if (new_config.audio_network_adaptor_config ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200711 config_.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700712 return;
713 }
Mirko Bonadei43564902020-01-29 15:29:36 +0000714 if (new_config.audio_network_adaptor_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200715 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700716 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200717 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100718 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
719 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700720 } else {
Alejandro Luebsc7710842020-03-05 12:05:50 -0800721 RTC_DLOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
722 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700723 }
724 });
725 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200726 channel_send_->CallEncoder(
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100727 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100728 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
729 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700730 }
731}
732
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200733void AudioSendStream::ReconfigureCNG(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700734 if (new_config.send_codec_spec->cng_payload_type ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200735 config_.send_codec_spec->cng_payload_type) {
ossu20a4b3f2017-04-27 02:08:52 -0700736 return;
737 }
738
ossu3b9ff382017-04-27 08:03:42 -0700739 // Register the CNG payload type if it's been added, don't do anything if CNG
740 // is removed. Payload types must not be redefined.
741 if (new_config.send_codec_spec->cng_payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200742 RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
743 new_config.send_codec_spec->format.clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700744 }
745
ossu20a4b3f2017-04-27 02:08:52 -0700746 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200747 channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
748 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
749 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
750 if (!sub_encoders.empty()) {
751 // Replace enc with its sub encoder. We need to put the sub
752 // encoder in a temporary first, since otherwise the old value
753 // of enc would be destroyed before the new value got assigned,
754 // which would be bad since the new value is a part of the old
755 // value.
756 auto tmp = std::move(sub_encoders[0]);
757 old_encoder = std::move(tmp);
758 }
759 if (new_config.send_codec_spec->cng_payload_type) {
760 AudioEncoderCngConfig config;
761 config.speech_encoder = std::move(old_encoder);
762 config.num_channels = config.speech_encoder->NumChannels();
763 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
764 config.vad_mode = Vad::kVadNormal;
765 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
766 } else {
767 *encoder_ptr = std::move(old_encoder);
768 }
769 });
ossu20a4b3f2017-04-27 02:08:52 -0700770}
771
772void AudioSendStream::ReconfigureBitrateObserver(
ossu20a4b3f2017-04-27 02:08:52 -0700773 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200774 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
ossu20a4b3f2017-04-27 02:08:52 -0700775 // Since the Config's default is for both of these to be -1, this test will
776 // allow us to configure the bitrate observer if the new config has bitrate
777 // limits set, but would only have us call RemoveBitrateObserver if we were
778 // previously configured with bitrate limits.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200779 if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
780 config_.max_bitrate_bps == new_config.max_bitrate_bps &&
781 config_.bitrate_priority == new_config.bitrate_priority &&
782 (TransportSeqNumId(config_) == TransportSeqNumId(new_config) ||
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100783 !audio_send_side_bwe_) &&
784 config_.audio_network_adaptor_config ==
785 new_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700786 return;
787 }
788
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200789 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200790 new_config.max_bitrate_bps != -1 && TransportSeqNumId(new_config) != 0) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200791 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100792 if (send_side_bwe_with_overhead_)
793 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100794 rtc::Event thread_sync_event;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200795 worker_queue_->PostTask([&] {
796 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100797 // We may get a callback immediately as the observer is registered, so
798 // make
799 // sure the bitrate limits in config_ are up-to-date.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200800 config_.min_bitrate_bps = new_config.min_bitrate_bps;
801 config_.max_bitrate_bps = new_config.max_bitrate_bps;
802
803 config_.bitrate_priority = new_config.bitrate_priority;
804 ConfigureBitrateObserver();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100805 thread_sync_event.Set();
806 });
807 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200808 rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700809 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200810 rtp_transport_->AccountForAudioPacketsInPacedSender(false);
811 RemoveBitrateObserver();
812 rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700813 }
814}
815
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100816void AudioSendStream::ConfigureBitrateObserver() {
817 // This either updates the current observer or adds a new observer.
818 // TODO(srte): Add overhead compensation here.
Daniel Lee93562522019-05-03 14:40:13 +0200819 auto constraints = GetMinMaxBitrateConstraints();
820
Sebastian Jansson0429f782019-10-03 18:32:45 +0200821 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200822 if (send_side_bwe_with_overhead_) {
Sebastian Jansson0429f782019-10-03 18:32:45 +0200823 if (use_legacy_overhead_calculation_) {
824 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
825 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100826 const TimeDelta kMinPacketDuration = TimeDelta::Millis(20);
Sebastian Jansson0429f782019-10-03 18:32:45 +0200827 DataRate max_overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100828 DataSize::Bytes(kOverheadPerPacket) / kMinPacketDuration;
Sebastian Jansson0429f782019-10-03 18:32:45 +0200829 priority_bitrate += max_overhead;
830 } else {
831 RTC_DCHECK(frame_length_range_);
832 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100833 DataSize::Bytes(total_packet_overhead_bytes_);
Jakob Ivarsson01ab0842020-03-06 09:59:56 +0100834 DataRate min_overhead = kOverheadPerPacket / frame_length_range_->second;
835 priority_bitrate += min_overhead;
Sebastian Jansson0429f782019-10-03 18:32:45 +0200836 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200837 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200838 if (allocation_settings_.priority_bitrate_raw)
839 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
840
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100841 bitrate_allocator_->AddObserver(
Daniel Lee93562522019-05-03 14:40:13 +0200842 this,
843 MediaStreamAllocationConfig{
844 constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200845 priority_bitrate.bps(), true,
846 allocation_settings_.bitrate_priority.value_or(
Jonas Olsson8f119ca2019-05-08 10:56:23 +0200847 config_.bitrate_priority)});
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100848 registered_with_allocator_ = true;
ossu20a4b3f2017-04-27 02:08:52 -0700849}
850
851void AudioSendStream::RemoveBitrateObserver() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200852 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerc572ff32018-11-07 08:43:50 +0100853 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700854 worker_queue_->PostTask([this, &thread_sync_event] {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100855 RTC_DCHECK_RUN_ON(worker_queue_);
856 registered_with_allocator_ = false;
ossu20a4b3f2017-04-27 02:08:52 -0700857 bitrate_allocator_->RemoveObserver(this);
858 thread_sync_event.Set();
859 });
860 thread_sync_event.Wait(rtc::Event::kForever);
861}
862
Daniel Lee93562522019-05-03 14:40:13 +0200863AudioSendStream::TargetAudioBitrateConstraints
864AudioSendStream::GetMinMaxBitrateConstraints() const {
865 TargetAudioBitrateConstraints constraints{
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100866 DataRate::BitsPerSec(config_.min_bitrate_bps),
867 DataRate::BitsPerSec(config_.max_bitrate_bps)};
Daniel Lee93562522019-05-03 14:40:13 +0200868
869 // If bitrates were explicitly overriden via field trial, use those values.
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200870 if (allocation_settings_.min_bitrate)
871 constraints.min = *allocation_settings_.min_bitrate;
872 if (allocation_settings_.max_bitrate)
873 constraints.max = *allocation_settings_.max_bitrate;
Daniel Lee93562522019-05-03 14:40:13 +0200874
Sebastian Jansson62aee932019-10-02 12:27:06 +0200875 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
876 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
877 RTC_DCHECK_GE(constraints.max, constraints.min);
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200878 if (send_side_bwe_with_overhead_) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200879 if (use_legacy_overhead_calculation_) {
880 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100881 const DataSize kOverheadPerPacket = DataSize::Bytes(20 + 8 + 10 + 12);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200882 const TimeDelta kMaxFrameLength =
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100883 TimeDelta::Millis(60); // Based on Opus spec
Sebastian Jansson62aee932019-10-02 12:27:06 +0200884 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
885 constraints.min += kMinOverhead;
886 constraints.max += kMinOverhead;
887 } else {
888 RTC_DCHECK(frame_length_range_);
889 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100890 DataSize::Bytes(total_packet_overhead_bytes_);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200891 constraints.min += kOverheadPerPacket / frame_length_range_->second;
892 constraints.max += kOverheadPerPacket / frame_length_range_->first;
893 }
Daniel Lee93562522019-05-03 14:40:13 +0200894 }
895 return constraints;
896}
897
ossu3b9ff382017-04-27 08:03:42 -0700898void AudioSendStream::RegisterCngPayloadType(int payload_type,
899 int clockrate_hz) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100900 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700901}
solenbergc7a8b082015-10-16 14:35:07 -0700902} // namespace internal
903} // namespace webrtc