blob: a44b55f95fb6ba109346a64ed727aaeff9a48b04 [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,
Marina Ciocead2aa8f92020-03-31 11:29:56 +0200130 config.rtp.ssrc,
131 config.frame_transformer)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100132
133AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100134 Clock* clock,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100135 const webrtc::AudioSendStream::Config& config,
136 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100137 TaskQueueFactory* task_queue_factory,
Niels Möller7d76a312018-10-26 12:57:07 +0200138 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200139 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100140 RtcEventLog* event_log,
141 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200142 const absl::optional<RtpState>& suspended_rtp_state,
Niels Möllerdced9f62018-11-19 10:27:07 +0100143 std::unique_ptr<voe::ChannelSendInterface> channel_send)
Sebastian Jansson977b3352019-03-04 17:43:34 +0100144 : clock_(clock),
Sebastian Jansson0b698262019-03-07 09:17:19 +0100145 worker_queue_(rtp_transport->GetWorkerQueue()),
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200146 audio_send_side_bwe_(field_trial::IsEnabled("WebRTC-Audio-SendSideBwe")),
147 allocate_audio_without_feedback_(
148 field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC")),
149 enable_audio_alr_probing_(
150 !field_trial::IsDisabled("WebRTC-Audio-AlrProbing")),
151 send_side_bwe_with_overhead_(
152 field_trial::IsEnabled("WebRTC-SendSideBwe-WithOverhead")),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800153 config_(Config(/*send_transport=*/nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700154 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 10:27:07 +0100155 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 02:08:52 -0700156 event_log_(event_log),
Sebastian Jansson62aee932019-10-02 12:27:06 +0200157 use_legacy_overhead_calculation_(
Sebastian Janssonbef818d2020-01-30 14:09:48 +0100158 field_trial::IsEnabled("WebRTC-Audio-LegacyOverhead")),
michaeltf4caaab2017-01-16 23:55:07 -0800159 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 12:57:07 +0200160 rtp_transport_(rtp_transport),
Sebastian Jansson6298b562020-01-14 17:55:19 +0100161 rtp_rtcp_module_(channel_send_->GetRtpRtcp()),
Sam Zackrissonff058162018-11-20 17:15:13 +0100162 suspended_rtp_state_(suspended_rtp_state) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100163 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100164 RTC_DCHECK(worker_queue_);
165 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100166 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100167 RTC_DCHECK(bitrate_allocator_);
Sebastian Jansson0b698262019-03-07 09:17:19 +0100168 RTC_DCHECK(rtp_transport);
169
ossuc3d4b482017-05-23 06:07:11 -0700170 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700171
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200172 ConfigureStream(config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700173
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200174 pacer_thread_checker_.Detach();
solenbergc7a8b082015-10-16 14:35:07 -0700175}
176
177AudioSendStream::~AudioSendStream() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200178 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100179 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100180 RTC_DCHECK(!sending_);
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200181 channel_send_->ResetSenderCongestionControlObjects();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100182 // Blocking call to synchronize state with worker queue to ensure that there
183 // are no pending tasks left that keeps references to audio.
184 rtc::Event thread_sync_event;
185 worker_queue_->PostTask([&] { thread_sync_event.Set(); });
186 thread_sync_event.Wait(rtc::Event::kForever);
solenbergc7a8b082015-10-16 14:35:07 -0700187}
188
eladalonabbc4302017-07-26 02:09:44 -0700189const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200190 RTC_DCHECK(worker_thread_checker_.IsCurrent());
eladalonabbc4302017-07-26 02:09:44 -0700191 return config_;
192}
193
ossu20a4b3f2017-04-27 02:08:52 -0700194void AudioSendStream::Reconfigure(
195 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200196 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200197 ConfigureStream(new_config, false);
ossu20a4b3f2017-04-27 02:08:52 -0700198}
199
Alex Narestcedd3512017-12-07 20:54:55 +0100200AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
201 const std::vector<RtpExtension>& extensions) {
202 ExtensionIds ids;
203 for (const auto& extension : extensions) {
204 if (extension.uri == RtpExtension::kAudioLevelUri) {
205 ids.audio_level = extension.id;
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200206 } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
207 ids.abs_send_time = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100208 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
209 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 10:24:32 -0700210 } else if (extension.uri == RtpExtension::kMidUri) {
211 ids.mid = extension.id;
Amit Hilbuch77938e62018-12-21 09:23:38 -0800212 } else if (extension.uri == RtpExtension::kRidUri) {
213 ids.rid = extension.id;
214 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
215 ids.repaired_rid = extension.id;
Minyue Li74dadc12020-03-05 11:33:13 +0100216 } else if (extension.uri == RtpExtension::kAbsoluteCaptureTimeUri) {
217 ids.abs_capture_time = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100218 }
219 }
220 return ids;
221}
222
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100223int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
224 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
225}
226
ossu20a4b3f2017-04-27 02:08:52 -0700227void AudioSendStream::ConfigureStream(
ossu20a4b3f2017-04-27 02:08:52 -0700228 const webrtc::AudioSendStream::Config& new_config,
229 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100230 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
231 << new_config.ToString();
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200232 UpdateEventLogStreamConfig(event_log_, new_config,
233 first_time ? nullptr : &config_);
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100234
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200235 const auto& old_config = config_;
ossu20a4b3f2017-04-27 02:08:52 -0700236
Niels Möllere9771992018-11-26 10:55:07 +0100237 // Configuration parameters which cannot be changed.
238 RTC_DCHECK(first_time ||
239 old_config.send_transport == new_config.send_transport);
Erik Språng70efdde2019-08-21 13:36:20 +0200240 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200241 if (suspended_rtp_state_ && first_time) {
242 rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
ossu20a4b3f2017-04-27 02:08:52 -0700243 }
244 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200245 channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700246 }
ossu20a4b3f2017-04-27 02:08:52 -0700247
Benjamin Wright84583f62018-10-04 14:22:34 -0700248 // Enable the frame encryptor if a new frame encryptor has been provided.
249 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200250 channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700251 }
252
Johannes Kron9190b822018-10-29 11:22:05 +0100253 if (first_time ||
Marina Ciocead2aa8f92020-03-31 11:29:56 +0200254 new_config.frame_transformer != old_config.frame_transformer) {
255 channel_send_->SetEncoderToPacketizerFrameTransformer(
256 new_config.frame_transformer);
257 }
258
259 if (first_time ||
Johannes Kron9190b822018-10-29 11:22:05 +0100260 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100261 rtp_rtcp_module_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100262 }
263
Alex Narestcedd3512017-12-07 20:54:55 +0100264 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
265 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
Yves Gerey17048012019-07-26 17:49:52 +0200266
ossu20a4b3f2017-04-27 02:08:52 -0700267 // Audio level indication
268 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200269 channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
270 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700271 }
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200272
273 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100274 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200275 kRtpExtensionAbsoluteSendTime);
276 if (new_ids.abs_send_time) {
Sebastian Janssonf39c8152019-10-14 17:32:21 +0200277 rtp_rtcp_module_->RegisterRtpHeaderExtension(AbsoluteSendTime::kUri,
278 new_ids.abs_send_time);
Sebastian Jansson71c6b562019-08-14 11:31:02 +0200279 }
280 }
281
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100282 bool transport_seq_num_id_changed =
283 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200284 if (first_time ||
285 (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
ossu1129df22017-06-30 01:38:56 -0700286 if (!first_time) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200287 channel_send_->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700288 }
289
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100290 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100291
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200292 if (audio_send_side_bwe_ && !allocate_audio_without_feedback_ &&
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200293 new_ids.transport_sequence_number != 0) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100294 rtp_rtcp_module_->RegisterRtpHeaderExtension(
295 TransportSequenceNumber::kUri, new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100296 // Probing in application limited region is only used in combination with
297 // send side congestion control, wich depends on feedback packets which
298 // requires transport sequence numbers to be enabled.
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200299 // Optionally request ALR probing but do not override any existing
300 // request from other streams.
301 if (enable_audio_alr_probing_) {
302 rtp_transport_->EnablePeriodicAlrProbing(true);
Niels Möller7d76a312018-10-26 12:57:07 +0200303 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200304 bandwidth_observer = rtp_transport_->GetBandwidthObserver();
ossu20a4b3f2017-04-27 02:08:52 -0700305 }
Sebastian Jansson0a6510d2019-10-04 09:31:08 +0200306 channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
307 bandwidth_observer);
ossu20a4b3f2017-04-27 02:08:52 -0700308 }
Steve Antonbb50ce52018-03-26 10:24:32 -0700309 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700310 if ((first_time || new_ids.mid != old_ids.mid ||
311 new_config.rtp.mid != old_config.rtp.mid) &&
312 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100313 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpMid::kUri, new_ids.mid);
314 rtp_rtcp_module_->SetMid(new_config.rtp.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700315 }
316
Amit Hilbuch77938e62018-12-21 09:23:38 -0800317 // RID RTP header extension
318 if ((first_time || new_ids.rid != old_ids.rid ||
319 new_ids.repaired_rid != old_ids.repaired_rid ||
320 new_config.rtp.rid != old_config.rtp.rid)) {
Sebastian Jansson6298b562020-01-14 17:55:19 +0100321 if (new_ids.rid != 0 || new_ids.repaired_rid != 0) {
322 if (new_config.rtp.rid.empty()) {
323 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(RtpStreamId::kUri);
324 } else if (new_ids.repaired_rid != 0) {
325 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
326 new_ids.repaired_rid);
327 } else {
328 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpStreamId::kUri,
329 new_ids.rid);
330 }
331 }
332 rtp_rtcp_module_->SetRid(new_config.rtp.rid);
Amit Hilbuch77938e62018-12-21 09:23:38 -0800333 }
334
Minyue Li74dadc12020-03-05 11:33:13 +0100335 if (first_time || new_ids.abs_capture_time != old_ids.abs_capture_time) {
336 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(
337 kRtpExtensionAbsoluteCaptureTime);
338 if (new_ids.abs_capture_time) {
339 rtp_rtcp_module_->RegisterRtpHeaderExtension(
340 AbsoluteCaptureTimeExtension::kUri, new_ids.abs_capture_time);
341 }
342 }
343
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200344 if (!ReconfigureSendCodec(new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100345 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700346 }
347
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100348 channel_send_->CallEncoder([this](AudioEncoder* encoder) {
349 if (!encoder) {
350 return;
351 }
352 worker_queue_->PostTask(
353 [this, length_range = encoder->GetFrameLengthRange()] {
354 RTC_DCHECK_RUN_ON(worker_queue_);
355 frame_length_range_ = length_range;
356 });
357 });
358
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200359 if (sending_) {
360 ReconfigureBitrateObserver(new_config);
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100361 }
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200362 config_ = new_config;
ossu20a4b3f2017-04-27 02:08:52 -0700363}
364
solenberg3a941542015-11-16 07:34:50 -0800365void AudioSendStream::Start() {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100366 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100367 if (sending_) {
368 return;
369 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200370 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
371 config_.max_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200372 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0)) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200373 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100374 if (send_side_bwe_with_overhead_)
375 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200376 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100377 rtc::Event thread_sync_event;
378 worker_queue_->PostTask([&] {
379 RTC_DCHECK_RUN_ON(worker_queue_);
380 ConfigureBitrateObserver();
381 thread_sync_event.Set();
382 });
383 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200384 } else {
385 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700386 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100387 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100388 sending_ = true;
389 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
390 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800391}
392
393void AudioSendStream::Stop() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200394 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100395 if (!sending_) {
396 return;
397 }
398
ossu20a4b3f2017-04-27 02:08:52 -0700399 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100400 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100401 sending_ = false;
402 audio_state()->RemoveSendingStream(this);
403}
404
405void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
406 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200407 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
408 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
409 audio_frame->sample_rate_hz_;
410 {
411 // Note: SendAudioData() passes the frame further down the pipeline and it
412 // may eventually get sent. But this method is invoked even if we are not
413 // connected, as long as we have an AudioSendStream (created as a result of
414 // an O/A exchange). This means that we are calculating audio levels whether
415 // or not we are sending samples.
416 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
417 // should move from send-streams to the local audio sources or tracks; a
418 // send-stream should not be required to read the microphone audio levels.
419 rtc::CritScope cs(&audio_level_lock_);
420 audio_level_.ComputeLevel(*audio_frame, duration);
421 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100422 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800423}
424
solenbergffbbcac2016-11-17 05:25:37 -0800425bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200426 int payload_frequency,
427 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800428 int duration_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200429 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100430 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
431 payload_frequency);
432 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100433}
434
solenberg94218532016-06-16 10:53:22 -0700435void AudioSendStream::SetMuted(bool muted) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200436 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerdced9f62018-11-19 10:27:07 +0100437 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700438}
439
solenbergc7a8b082015-10-16 14:35:07 -0700440webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100441 return GetStats(true);
442}
443
444webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
445 bool has_remote_tracks) const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200446 RTC_DCHECK(worker_thread_checker_.IsCurrent());
solenberg85a04962015-10-27 03:35:21 -0700447 webrtc::AudioSendStream::Stats stats;
448 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100449 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700450
Niels Möllerdced9f62018-11-19 10:27:07 +0100451 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200452 stats.payload_bytes_sent = call_stats.payload_bytes_sent;
453 stats.header_and_padding_bytes_sent =
454 call_stats.header_and_padding_bytes_sent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200455 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
solenberg85a04962015-10-27 03:35:21 -0700456 stats.packets_sent = call_stats.packetsSent;
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200457 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
solenberg8b85de22015-11-16 09:48:04 -0800458 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
459 // returns 0 to indicate an error value.
460 if (call_stats.rttMs > 0) {
461 stats.rtt_ms = call_stats.rttMs;
462 }
ossu20a4b3f2017-04-27 02:08:52 -0700463 if (config_.send_codec_spec) {
464 const auto& spec = *config_.send_codec_spec;
465 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100466 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700467
468 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100469 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800470 // Lookup report for send ssrc only.
471 if (block.source_SSRC == stats.local_ssrc) {
472 stats.packets_lost = block.cumulative_num_packets_lost;
473 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
ossu20a4b3f2017-04-27 02:08:52 -0700474 // Convert timestamps to milliseconds.
475 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800476 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700477 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700478 }
solenberg8b85de22015-11-16 09:48:04 -0800479 break;
solenberg85a04962015-10-27 03:35:21 -0700480 }
481 }
482 }
483
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200484 {
485 rtc::CritScope cs(&audio_level_lock_);
486 stats.audio_level = audio_level_.LevelFullRange();
487 stats.total_input_energy = audio_level_.TotalEnergy();
488 stats.total_input_duration = audio_level_.TotalDuration();
489 }
solenberg796b8f92017-03-01 17:02:23 -0800490
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100491 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100492 stats.ana_statistics = channel_send_->GetANAStatistics();
Per Åhgrencc73ed32020-04-26 23:56:17 +0200493
494 AudioProcessing* ap = audio_state_->audio_processing();
495 if (ap) {
496 stats.apm_statistics = ap->GetStatistics(has_remote_tracks);
497 }
solenberg85a04962015-10-27 03:35:21 -0700498
Henrik Boström6e436d12019-05-27 12:19:33 +0200499 stats.report_block_datas = std::move(call_stats.report_block_datas);
500
solenberg85a04962015-10-27 03:35:21 -0700501 return stats;
502}
503
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100504void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
pbos1ba8d392016-05-01 20:18:34 -0700505 // TODO(solenberg): Tests call this function on a network thread, libjingle
506 // calls on the worker thread. We should move towards always using a network
507 // thread. Then this check can be enabled.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200508 // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100509 channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700510}
511
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200512uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200513 RTC_DCHECK_RUN_ON(worker_queue_);
Daniel Lee93562522019-05-03 14:40:13 +0200514 // Pick a target bitrate between the constraints. Overrules the allocator if
515 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
516 // higher than max to allow for e.g. extra FEC.
517 auto constraints = GetMinMaxBitrateConstraints();
518 update.target_bitrate.Clamp(constraints.min, constraints.max);
Jakob Ivarsson0c964492020-03-11 09:18:59 +0100519 update.stable_target_bitrate.Clamp(constraints.min, constraints.max);
mflodman86cc6ff2016-07-26 04:44:06 -0700520
Sebastian Jansson254d8692018-11-21 19:19:00 +0100521 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 04:44:06 -0700522
523 // The amount of audio protection is not exposed by the encoder, hence
524 // always returning 0.
525 return 0;
526}
527
Anton Sukhanov626015d2019-02-04 15:16:06 -0800528void AudioSendStream::SetTransportOverhead(
529 int transport_overhead_per_packet_bytes) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200530 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Anton Sukhanov626015d2019-02-04 15:16:06 -0800531 rtc::CritScope cs(&overhead_per_packet_lock_);
532 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
533 UpdateOverheadForEncoder();
534}
535
536void AudioSendStream::OnOverheadChanged(
537 size_t overhead_bytes_per_packet_bytes) {
538 rtc::CritScope cs(&overhead_per_packet_lock_);
539 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
540 UpdateOverheadForEncoder();
541}
542
543void AudioSendStream::UpdateOverheadForEncoder() {
544 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700545 if (overhead_per_packet_bytes == 0) {
546 return; // Overhead is not known yet, do not tell the encoder.
547 }
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100548 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
549 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
Anton Sukhanov626015d2019-02-04 15:16:06 -0800550 });
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100551 worker_queue_->PostTask([this, overhead_per_packet_bytes] {
552 RTC_DCHECK_RUN_ON(worker_queue_);
553 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
554 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
555 if (registered_with_allocator_) {
556 ConfigureBitrateObserver();
557 }
558 }
559 });
Anton Sukhanov626015d2019-02-04 15:16:06 -0800560}
561
562size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
563 rtc::CritScope cs(&overhead_per_packet_lock_);
564 return GetPerPacketOverheadBytes();
565}
566
567size_t AudioSendStream::GetPerPacketOverheadBytes() const {
568 return transport_overhead_per_packet_bytes_ +
569 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 02:50:09 -0800570}
571
ossuc3d4b482017-05-23 06:07:11 -0700572RtpState AudioSendStream::GetRtpState() const {
573 return rtp_rtcp_module_->GetRtpState();
574}
575
Niels Möllerdced9f62018-11-19 10:27:07 +0100576const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
577 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100578}
579
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100580internal::AudioState* AudioSendStream::audio_state() {
581 internal::AudioState* audio_state =
582 static_cast<internal::AudioState*>(audio_state_.get());
583 RTC_DCHECK(audio_state);
584 return audio_state;
585}
586
587const internal::AudioState* AudioSendStream::audio_state() const {
588 internal::AudioState* audio_state =
589 static_cast<internal::AudioState*>(audio_state_.get());
590 RTC_DCHECK(audio_state);
591 return audio_state;
592}
593
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100594void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
595 size_t num_channels) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200596 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100597 encoder_sample_rate_hz_ = sample_rate_hz;
598 encoder_num_channels_ = num_channels;
599 if (sending_) {
600 // Update AudioState's information about the stream.
601 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
602 }
603}
604
minyue7a973442016-10-20 03:27:12 -0700605// Apply current codec settings to a single voe::Channel used for sending.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200606bool AudioSendStream::SetupSendCodec(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700607 RTC_DCHECK(new_config.send_codec_spec);
608 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700609
610 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700611 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100612 new_config.encoder_factory->MakeAudioEncoder(
613 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700614
ossu20a4b3f2017-04-27 02:08:52 -0700615 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200616 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
617 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700618 return false;
619 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200620
ossu20a4b3f2017-04-27 02:08:52 -0700621 // If a bitrate has been specified for the codec, use it over the
622 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100623 if (spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700624 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700625 }
626
ossu20a4b3f2017-04-27 02:08:52 -0700627 // Enable ANA if configured (currently only used by Opus).
Mirko Bonadei43564902020-01-29 15:29:36 +0000628 if (new_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700629 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200630 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100631 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
632 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700633 } else {
Alejandro Luebsc7710842020-03-05 12:05:50 -0800634 RTC_DLOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
635 << new_config.rtp.ssrc;
minyue6b825df2016-10-31 04:08:32 -0700636 }
minyue7a973442016-10-20 03:27:12 -0700637 }
638
ossu20a4b3f2017-04-27 02:08:52 -0700639 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
640 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100641 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700642 cng_config.num_channels = encoder->NumChannels();
643 cng_config.payload_type = *spec.cng_payload_type;
644 cng_config.speech_encoder = std::move(encoder);
645 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100646 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700647
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200648 RegisterCngPayloadType(*spec.cng_payload_type,
649 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700650 }
ossu20a4b3f2017-04-27 02:08:52 -0700651
Anton Sukhanov626015d2019-02-04 15:16:06 -0800652 // Set currently known overhead (used in ANA, opus only).
653 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
654 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200655 rtc::CritScope cs(&overhead_per_packet_lock_);
656 if (GetPerPacketOverheadBytes() > 0) {
657 encoder->OnReceivedOverhead(GetPerPacketOverheadBytes());
Bjorn A Mellem413ccc42019-04-26 15:41:05 -0700658 }
Anton Sukhanov626015d2019-02-04 15:16:06 -0800659 }
660
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200661 StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
662 channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
663 std::move(encoder));
Anton Sukhanov626015d2019-02-04 15:16:06 -0800664
minyue7a973442016-10-20 03:27:12 -0700665 return true;
666}
667
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200668bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
669 const auto& old_config = config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200670
671 if (!new_config.send_codec_spec) {
672 // We cannot de-configure a send codec. So we will do nothing.
673 // By design, the send codec should have not been configured.
674 RTC_DCHECK(!old_config.send_codec_spec);
675 return true;
676 }
677
678 if (new_config.send_codec_spec == old_config.send_codec_spec &&
679 new_config.audio_network_adaptor_config ==
680 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700681 return true;
682 }
683
684 // If we have no encoder, or the format or payload type's changed, create a
685 // new encoder.
686 if (!old_config.send_codec_spec ||
687 new_config.send_codec_spec->format !=
688 old_config.send_codec_spec->format ||
689 new_config.send_codec_spec->payload_type !=
690 old_config.send_codec_spec->payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200691 return SetupSendCodec(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700692 }
693
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200694 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700695 new_config.send_codec_spec->target_bitrate_bps;
696 // If a bitrate has been specified for the codec, use it over the
697 // codec's default.
Christoffer Rodbro110c64b2019-03-06 09:51:08 +0100698 if (new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700699 new_target_bitrate_bps !=
700 old_config.send_codec_spec->target_bitrate_bps) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200701 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700702 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
703 });
704 }
705
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200706 ReconfigureANA(new_config);
707 ReconfigureCNG(new_config);
ossu20a4b3f2017-04-27 02:08:52 -0700708
Anton Sukhanov626015d2019-02-04 15:16:06 -0800709 // Set currently known overhead (used in ANA, opus only).
710 {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200711 rtc::CritScope cs(&overhead_per_packet_lock_);
712 UpdateOverheadForEncoder();
Anton Sukhanov626015d2019-02-04 15:16:06 -0800713 }
714
ossu20a4b3f2017-04-27 02:08:52 -0700715 return true;
716}
717
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200718void AudioSendStream::ReconfigureANA(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700719 if (new_config.audio_network_adaptor_config ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200720 config_.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700721 return;
722 }
Mirko Bonadei43564902020-01-29 15:29:36 +0000723 if (new_config.audio_network_adaptor_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200724 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700725 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200726 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100727 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
728 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700729 } else {
Alejandro Luebsc7710842020-03-05 12:05:50 -0800730 RTC_DLOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
731 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700732 }
733 });
734 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200735 channel_send_->CallEncoder(
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100736 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100737 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
738 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700739 }
740}
741
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200742void AudioSendStream::ReconfigureCNG(const Config& new_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700743 if (new_config.send_codec_spec->cng_payload_type ==
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200744 config_.send_codec_spec->cng_payload_type) {
ossu20a4b3f2017-04-27 02:08:52 -0700745 return;
746 }
747
ossu3b9ff382017-04-27 08:03:42 -0700748 // Register the CNG payload type if it's been added, don't do anything if CNG
749 // is removed. Payload types must not be redefined.
750 if (new_config.send_codec_spec->cng_payload_type) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200751 RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
752 new_config.send_codec_spec->format.clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700753 }
754
ossu20a4b3f2017-04-27 02:08:52 -0700755 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200756 channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
757 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
758 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
759 if (!sub_encoders.empty()) {
760 // Replace enc with its sub encoder. We need to put the sub
761 // encoder in a temporary first, since otherwise the old value
762 // of enc would be destroyed before the new value got assigned,
763 // which would be bad since the new value is a part of the old
764 // value.
765 auto tmp = std::move(sub_encoders[0]);
766 old_encoder = std::move(tmp);
767 }
768 if (new_config.send_codec_spec->cng_payload_type) {
769 AudioEncoderCngConfig config;
770 config.speech_encoder = std::move(old_encoder);
771 config.num_channels = config.speech_encoder->NumChannels();
772 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
773 config.vad_mode = Vad::kVadNormal;
774 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
775 } else {
776 *encoder_ptr = std::move(old_encoder);
777 }
778 });
ossu20a4b3f2017-04-27 02:08:52 -0700779}
780
781void AudioSendStream::ReconfigureBitrateObserver(
ossu20a4b3f2017-04-27 02:08:52 -0700782 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200783 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
ossu20a4b3f2017-04-27 02:08:52 -0700784 // Since the Config's default is for both of these to be -1, this test will
785 // allow us to configure the bitrate observer if the new config has bitrate
786 // limits set, but would only have us call RemoveBitrateObserver if we were
787 // previously configured with bitrate limits.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200788 if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
789 config_.max_bitrate_bps == new_config.max_bitrate_bps &&
790 config_.bitrate_priority == new_config.bitrate_priority &&
791 (TransportSeqNumId(config_) == TransportSeqNumId(new_config) ||
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100792 !audio_send_side_bwe_) &&
793 config_.audio_network_adaptor_config ==
794 new_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700795 return;
796 }
797
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200798 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
Sebastian Janssoncd0eedb2019-10-10 13:52:26 +0200799 new_config.max_bitrate_bps != -1 && TransportSeqNumId(new_config) != 0) {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200800 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonc3eb9fd2020-01-29 17:42:52 +0100801 if (send_side_bwe_with_overhead_)
802 rtp_transport_->IncludeOverheadInPacedSender();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100803 rtc::Event thread_sync_event;
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200804 worker_queue_->PostTask([&] {
805 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100806 // We may get a callback immediately as the observer is registered, so
807 // make
808 // sure the bitrate limits in config_ are up-to-date.
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200809 config_.min_bitrate_bps = new_config.min_bitrate_bps;
810 config_.max_bitrate_bps = new_config.max_bitrate_bps;
811
812 config_.bitrate_priority = new_config.bitrate_priority;
813 ConfigureBitrateObserver();
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100814 thread_sync_event.Set();
815 });
816 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200817 rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700818 } else {
Sebastian Jansson35cf9e72019-10-04 09:30:32 +0200819 rtp_transport_->AccountForAudioPacketsInPacedSender(false);
820 RemoveBitrateObserver();
821 rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700822 }
823}
824
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100825void AudioSendStream::ConfigureBitrateObserver() {
826 // This either updates the current observer or adds a new observer.
827 // TODO(srte): Add overhead compensation here.
Daniel Lee93562522019-05-03 14:40:13 +0200828 auto constraints = GetMinMaxBitrateConstraints();
829
Sebastian Jansson0429f782019-10-03 18:32:45 +0200830 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200831 if (send_side_bwe_with_overhead_) {
Sebastian Jansson0429f782019-10-03 18:32:45 +0200832 if (use_legacy_overhead_calculation_) {
833 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
834 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100835 const TimeDelta kMinPacketDuration = TimeDelta::Millis(20);
Sebastian Jansson0429f782019-10-03 18:32:45 +0200836 DataRate max_overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100837 DataSize::Bytes(kOverheadPerPacket) / kMinPacketDuration;
Sebastian Jansson0429f782019-10-03 18:32:45 +0200838 priority_bitrate += max_overhead;
839 } else {
840 RTC_DCHECK(frame_length_range_);
841 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100842 DataSize::Bytes(total_packet_overhead_bytes_);
Jakob Ivarsson01ab0842020-03-06 09:59:56 +0100843 DataRate min_overhead = kOverheadPerPacket / frame_length_range_->second;
844 priority_bitrate += min_overhead;
Sebastian Jansson0429f782019-10-03 18:32:45 +0200845 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200846 }
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200847 if (allocation_settings_.priority_bitrate_raw)
848 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
849
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100850 bitrate_allocator_->AddObserver(
Daniel Lee93562522019-05-03 14:40:13 +0200851 this,
852 MediaStreamAllocationConfig{
853 constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200854 priority_bitrate.bps(), true,
855 allocation_settings_.bitrate_priority.value_or(
Jonas Olsson8f119ca2019-05-08 10:56:23 +0200856 config_.bitrate_priority)});
Jakob Ivarssond14525e2020-03-06 09:49:29 +0100857 registered_with_allocator_ = true;
ossu20a4b3f2017-04-27 02:08:52 -0700858}
859
860void AudioSendStream::RemoveBitrateObserver() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200861 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerc572ff32018-11-07 08:43:50 +0100862 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700863 worker_queue_->PostTask([this, &thread_sync_event] {
Sebastian Jansson8672cac2019-03-01 15:57:55 +0100864 RTC_DCHECK_RUN_ON(worker_queue_);
865 registered_with_allocator_ = false;
ossu20a4b3f2017-04-27 02:08:52 -0700866 bitrate_allocator_->RemoveObserver(this);
867 thread_sync_event.Set();
868 });
869 thread_sync_event.Wait(rtc::Event::kForever);
870}
871
Daniel Lee93562522019-05-03 14:40:13 +0200872AudioSendStream::TargetAudioBitrateConstraints
873AudioSendStream::GetMinMaxBitrateConstraints() const {
874 TargetAudioBitrateConstraints constraints{
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100875 DataRate::BitsPerSec(config_.min_bitrate_bps),
876 DataRate::BitsPerSec(config_.max_bitrate_bps)};
Daniel Lee93562522019-05-03 14:40:13 +0200877
878 // If bitrates were explicitly overriden via field trial, use those values.
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200879 if (allocation_settings_.min_bitrate)
880 constraints.min = *allocation_settings_.min_bitrate;
881 if (allocation_settings_.max_bitrate)
882 constraints.max = *allocation_settings_.max_bitrate;
Daniel Lee93562522019-05-03 14:40:13 +0200883
Sebastian Jansson62aee932019-10-02 12:27:06 +0200884 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
885 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
886 RTC_DCHECK_GE(constraints.max, constraints.min);
Sebastian Janssonf23131f2019-10-03 10:03:55 +0200887 if (send_side_bwe_with_overhead_) {
Sebastian Jansson62aee932019-10-02 12:27:06 +0200888 if (use_legacy_overhead_calculation_) {
889 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100890 const DataSize kOverheadPerPacket = DataSize::Bytes(20 + 8 + 10 + 12);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200891 const TimeDelta kMaxFrameLength =
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100892 TimeDelta::Millis(60); // Based on Opus spec
Sebastian Jansson62aee932019-10-02 12:27:06 +0200893 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
894 constraints.min += kMinOverhead;
895 constraints.max += kMinOverhead;
896 } else {
897 RTC_DCHECK(frame_length_range_);
898 const DataSize kOverheadPerPacket =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100899 DataSize::Bytes(total_packet_overhead_bytes_);
Sebastian Jansson62aee932019-10-02 12:27:06 +0200900 constraints.min += kOverheadPerPacket / frame_length_range_->second;
901 constraints.max += kOverheadPerPacket / frame_length_range_->first;
902 }
Daniel Lee93562522019-05-03 14:40:13 +0200903 }
904 return constraints;
905}
906
ossu3b9ff382017-04-27 08:03:42 -0700907void AudioSendStream::RegisterCngPayloadType(int payload_type,
908 int clockrate_hz) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100909 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
ossu3b9ff382017-04-27 08:03:42 -0700910}
solenbergc7a8b082015-10-16 14:35:07 -0700911} // namespace internal
912} // namespace webrtc