blob: 401e8595b208314eaeea0599a89400e065bac728 [file] [log] [blame]
solenbergc7a8b082015-10-16 21:35:071/*
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 04:47:3111#include "audio/audio_send_stream.h"
solenbergc7a8b082015-10-16 21:35:0712
Mirko Bonadei317a1f02019-09-17 15:06:1813#include <memory>
solenbergc7a8b082015-10-16 21:35:0714#include <string>
ossu20a4b3f2017-04-27 09:08:5215#include <utility>
16#include <vector>
solenbergc7a8b082015-10-16 21:35:0717
Yves Gerey988cc082018-10-23 10:03:0118#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 17:11:0022#include "api/crypto/frame_encryptor_interface.h"
Artem Titov741daaf2019-03-21 13:37:3623#include "api/function_view.h"
Danil Chapovalov83bbe912019-08-07 10:24:5324#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller65f17ca2019-09-12 11:59:3625#include "api/transport/media/media_transport_config.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3126#include "audio/audio_state.h"
Yves Gerey988cc082018-10-23 10:03:0127#include "audio/channel_send.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3128#include "audio/conversion.h"
Yves Gerey988cc082018-10-23 10:03:0129#include "call/rtp_config.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3130#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey988cc082018-10-23 10:03:0131#include "common_audio/vad/include/vad.h"
Oskar Sundbom56ef3052018-10-30 15:11:0232#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
Oskar Sundbom56ef3052018-10-30 15:11:0233#include "logging/rtc_event_log/rtc_stream_config.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3134#include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
Yves Gerey988cc082018-10-23 10:03:0135#include "modules/audio_processing/include/audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3136#include "rtc_base/checks.h"
37#include "rtc_base/event.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3138#include "rtc_base/logging.h"
Jonas Olssonabbe8412018-04-03 11:40:0539#include "rtc_base/strings/audio_format_to_string.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3140#include "rtc_base/task_queue.h"
Alex Narestcedd3512017-12-07 19:54:5541#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 21:35:0742
43namespace webrtc {
Fredrik Solenberg8f5787a2018-01-11 12:52:3044namespace {
eladalonedd6eea2017-05-25 07:15:3545// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 18:04:4846constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
47constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
48constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
49
Oskar Sundbom56ef3052018-10-30 15:11:0250void UpdateEventLogStreamConfig(RtcEventLog* event_log,
51 const AudioSendStream::Config& config,
52 const AudioSendStream::Config* old_config) {
53 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
54 // Only update if any of the things we log have changed.
55 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
56 const absl::optional<SendCodecSpec>& b) {
57 if (a.has_value() && b.has_value()) {
58 return a->format.name == b->format.name &&
59 a->payload_type == b->payload_type;
60 }
61 return !a.has_value() && !b.has_value();
62 };
63
64 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
65 config.rtp.extensions == old_config->rtp.extensions &&
66 payload_types_equal(config.send_codec_spec,
67 old_config->send_codec_spec)) {
68 return;
69 }
70
Mirko Bonadei317a1f02019-09-17 15:06:1871 auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
Oskar Sundbom56ef3052018-10-30 15:11:0272 rtclog_config->local_ssrc = config.rtp.ssrc;
73 rtclog_config->rtp_extensions = config.rtp.extensions;
74 if (config.send_codec_spec) {
75 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
76 config.send_codec_spec->payload_type, 0);
77 }
Mirko Bonadei317a1f02019-09-17 15:06:1878 event_log->Log(std::make_unique<RtcEventAudioSendStreamConfig>(
Oskar Sundbom56ef3052018-10-30 15:11:0279 std::move(rtclog_config)));
80}
ossu20a4b3f2017-04-27 09:08:5281} // namespace
82
Sebastian Janssonf23131f2019-10-03 08:03:5583constexpr char AudioAllocationConfig::kKey[];
84
85std::unique_ptr<StructParametersParser> AudioAllocationConfig::Parser() {
86 return StructParametersParser::Create( //
87 "min", &min_bitrate, //
88 "max", &max_bitrate, //
89 "prio_rate", &priority_bitrate, //
90 "prio_rate_raw", &priority_bitrate_raw, //
91 "rate_prio", &bitrate_priority);
92}
93
94AudioAllocationConfig::AudioAllocationConfig() {
95 Parser()->Parse(field_trial::FindFullName(kKey));
96 if (priority_bitrate_raw && !priority_bitrate.IsZero()) {
97 RTC_LOG(LS_WARNING) << "'priority_bitrate' and '_raw' are mutually "
98 "exclusive but both were configured.";
99 }
100}
101
102namespace internal {
solenberg566ef242015-11-06 23:34:49103AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 16:43:34104 Clock* clock,
solenberg566ef242015-11-06 23:34:49105 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 09:26:18106 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 13:50:30107 TaskQueueFactory* task_queue_factory,
Fredrik Solenberg8f5787a2018-01-11 12:52:30108 ProcessThread* module_process_thread,
Niels Möller7d76a312018-10-26 10:57:07109 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 11:00:40110 BitrateAllocatorInterface* bitrate_allocator,
michaelt9332b7d2016-11-30 15:51:13111 RtcEventLog* event_log,
ossuc3d4b482017-05-23 13:07:11112 RtcpRttStats* rtcp_rtt_stats,
Sam Zackrissonff058162018-11-20 16:15:13113 const absl::optional<RtpState>& suspended_rtp_state)
Sebastian Jansson977b3352019-03-04 16:43:34114 : AudioSendStream(clock,
115 config,
Fredrik Solenberg8f5787a2018-01-11 12:52:30116 audio_state,
Sebastian Jansson44dd9f22019-03-08 13:50:30117 task_queue_factory,
Niels Möller7d76a312018-10-26 10:57:07118 rtp_transport,
Fredrik Solenberg8f5787a2018-01-11 12:52:30119 bitrate_allocator,
120 event_log,
121 rtcp_rtt_stats,
122 suspended_rtp_state,
Sebastian Jansson977b3352019-03-04 16:43:34123 voe::CreateChannelSend(clock,
Sebastian Jansson44dd9f22019-03-08 13:50:30124 task_queue_factory,
Niels Möllerdced9f62018-11-19 09:27:07125 module_process_thread,
Anton Sukhanov4f08faa2019-05-21 18:12:57126 config.media_transport_config,
Anton Sukhanov626015d2019-02-04 23:16:06127 /*overhead_observer=*/this,
Niels Möllere9771992018-11-26 09:55:07128 config.send_transport,
Niels Möllerdced9f62018-11-19 09:27:07129 rtcp_rtt_stats,
130 event_log,
131 config.frame_encryptor,
132 config.crypto_options,
133 config.rtp.extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 13:20:15134 config.rtcp_report_interval_ms,
135 config.rtp.ssrc)) {}
Fredrik Solenberg8f5787a2018-01-11 12:52:30136
137AudioSendStream::AudioSendStream(
Sebastian Jansson977b3352019-03-04 16:43:34138 Clock* clock,
Fredrik Solenberg8f5787a2018-01-11 12:52:30139 const webrtc::AudioSendStream::Config& config,
140 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
Sebastian Jansson44dd9f22019-03-08 13:50:30141 TaskQueueFactory* task_queue_factory,
Niels Möller7d76a312018-10-26 10:57:07142 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 11:00:40143 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 12:52:30144 RtcEventLog* event_log,
145 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 10:28:07146 const absl::optional<RtpState>& suspended_rtp_state,
Niels Möllerdced9f62018-11-19 09:27:07147 std::unique_ptr<voe::ChannelSendInterface> channel_send)
Sebastian Jansson977b3352019-03-04 16:43:34148 : clock_(clock),
Sebastian Jansson0b698262019-03-07 08:17:19149 worker_queue_(rtp_transport->GetWorkerQueue()),
Sebastian Janssonf23131f2019-10-03 08:03:55150 audio_send_side_bwe_(field_trial::IsEnabled("WebRTC-Audio-SendSideBwe")),
151 allocate_audio_without_feedback_(
152 field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC")),
153 enable_audio_alr_probing_(
154 !field_trial::IsDisabled("WebRTC-Audio-AlrProbing")),
155 send_side_bwe_with_overhead_(
156 field_trial::IsEnabled("WebRTC-SendSideBwe-WithOverhead")),
Anton Sukhanov4f08faa2019-05-21 18:12:57157 config_(Config(/*send_transport=*/nullptr, MediaTransportConfig())),
mflodman86cc6ff2016-07-26 11:44:06158 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 09:27:07159 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 09:08:52160 event_log_(event_log),
Sebastian Jansson62aee932019-10-02 10:27:06161 use_legacy_overhead_calculation_(
162 !field_trial::IsDisabled("WebRTC-Audio-LegacyOverhead")),
michaeltf4caaab2017-01-17 07:55:07163 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 10:57:07164 rtp_transport_(rtp_transport),
elad.alond12a8e12017-03-23 18:04:48165 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
166 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 13:07:11167 kRecoverablePacketLossRateMinNumAckedPairs),
168 rtp_rtcp_module_(nullptr),
Sam Zackrissonff058162018-11-20 16:15:13169 suspended_rtp_state_(suspended_rtp_state) {
Jonas Olsson24ea8222018-01-25 09:14:29170 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 12:52:30171 RTC_DCHECK(worker_queue_);
172 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 09:27:07173 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 12:52:30174 RTC_DCHECK(bitrate_allocator_);
Sebastian Jansson0b698262019-03-07 08:17:19175 // Currently we require the rtp transport even when media transport is used.
176 RTC_DCHECK(rtp_transport);
177
Niels Möller7d76a312018-10-26 10:57:07178 // TODO(nisse): Eventually, we should have only media_transport. But for the
179 // time being, we can have either. When media transport is injected, there
180 // should be no rtp_transport, and below check should be strengthened to XOR
181 // (either rtp_transport or media_transport but not both).
Anton Sukhanov4f08faa2019-05-21 18:12:57182 RTC_DCHECK(rtp_transport || config.media_transport_config.media_transport);
183 if (config.media_transport_config.media_transport) {
Anton Sukhanov626015d2019-02-04 23:16:06184 // TODO(sukhanov): Currently media transport audio overhead is considered
185 // constant, we will not get overhead_observer calls when using
186 // media_transport. In the future when we introduce RTP media transport we
187 // should make audio overhead interface consistent and work for both RTP and
188 // non-RTP implementations.
189 audio_overhead_per_packet_bytes_ =
Anton Sukhanov4f08faa2019-05-21 18:12:57190 config.media_transport_config.media_transport->GetAudioPacketOverhead();
Anton Sukhanov626015d2019-02-04 23:16:06191 }
Niels Möllerdced9f62018-11-19 09:27:07192 rtp_rtcp_module_ = channel_send_->GetRtpRtcp();
ossuc3d4b482017-05-23 13:07:11193 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 07:57:13194
Sebastian Jansson35cf9e72019-10-04 07:30:32195 ConfigureStream(config, true);
elad.alond12a8e12017-03-23 18:04:48196
Sebastian Janssonc01367d2019-04-08 13:20:44197 pacer_thread_checker_.Detach();
Niels Möller7d76a312018-10-26 10:57:07198 if (rtp_transport_) {
199 // Signal congestion controller this object is ready for OnPacket*
200 // callbacks.
201 rtp_transport_->RegisterPacketFeedbackObserver(this);
202 }
solenbergc7a8b082015-10-16 21:35:07203}
204
205AudioSendStream::~AudioSendStream() {
Sebastian Janssonc01367d2019-04-08 13:20:44206 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Jonas Olsson24ea8222018-01-25 09:14:29207 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 15:42:15208 RTC_DCHECK(!sending_);
Niels Möller7d76a312018-10-26 10:57:07209 if (rtp_transport_) {
210 rtp_transport_->DeRegisterPacketFeedbackObserver(this);
Niels Möllerdced9f62018-11-19 09:27:07211 channel_send_->ResetSenderCongestionControlObjects();
Niels Möller7d76a312018-10-26 10:57:07212 }
Sebastian Jansson8672cac2019-03-01 14:57:55213 // Blocking call to synchronize state with worker queue to ensure that there
214 // are no pending tasks left that keeps references to audio.
215 rtc::Event thread_sync_event;
216 worker_queue_->PostTask([&] { thread_sync_event.Set(); });
217 thread_sync_event.Wait(rtc::Event::kForever);
solenbergc7a8b082015-10-16 21:35:07218}
219
eladalonabbc4302017-07-26 09:09:44220const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
Sebastian Janssonc01367d2019-04-08 13:20:44221 RTC_DCHECK(worker_thread_checker_.IsCurrent());
eladalonabbc4302017-07-26 09:09:44222 return config_;
223}
224
ossu20a4b3f2017-04-27 09:08:52225void AudioSendStream::Reconfigure(
226 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Janssonc01367d2019-04-08 13:20:44227 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Sebastian Jansson35cf9e72019-10-04 07:30:32228 ConfigureStream(new_config, false);
ossu20a4b3f2017-04-27 09:08:52229}
230
Alex Narestcedd3512017-12-07 19:54:55231AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
232 const std::vector<RtpExtension>& extensions) {
233 ExtensionIds ids;
234 for (const auto& extension : extensions) {
235 if (extension.uri == RtpExtension::kAudioLevelUri) {
236 ids.audio_level = extension.id;
Sebastian Jansson71c6b562019-08-14 09:31:02237 } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
238 ids.abs_send_time = extension.id;
Alex Narestcedd3512017-12-07 19:54:55239 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
240 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 17:24:32241 } else if (extension.uri == RtpExtension::kMidUri) {
242 ids.mid = extension.id;
Amit Hilbuch77938e62018-12-21 17:23:38243 } else if (extension.uri == RtpExtension::kRidUri) {
244 ids.rid = extension.id;
245 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
246 ids.repaired_rid = extension.id;
Alex Narestcedd3512017-12-07 19:54:55247 }
248 }
249 return ids;
250}
251
Sebastian Jansson470a5ea2019-01-23 11:37:49252int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
253 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
254}
255
ossu20a4b3f2017-04-27 09:08:52256void AudioSendStream::ConfigureStream(
ossu20a4b3f2017-04-27 09:08:52257 const webrtc::AudioSendStream::Config& new_config,
258 bool first_time) {
Jonas Olsson24ea8222018-01-25 09:14:29259 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
260 << new_config.ToString();
Sebastian Jansson35cf9e72019-10-04 07:30:32261 UpdateEventLogStreamConfig(event_log_, new_config,
262 first_time ? nullptr : &config_);
Oskar Sundbom56ef3052018-10-30 15:11:02263
Sebastian Jansson35cf9e72019-10-04 07:30:32264 const auto& old_config = config_;
ossu20a4b3f2017-04-27 09:08:52265
Sebastian Jansson35cf9e72019-10-04 07:30:32266 config_cs_.Enter();
Yves Gerey17048012019-07-26 15:49:52267
Niels Möllere9771992018-11-26 09:55:07268 // Configuration parameters which cannot be changed.
269 RTC_DCHECK(first_time ||
270 old_config.send_transport == new_config.send_transport);
Erik Språng70efdde2019-08-21 11:36:20271 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
Sebastian Jansson35cf9e72019-10-04 07:30:32272 if (suspended_rtp_state_ && first_time) {
273 rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
ossu20a4b3f2017-04-27 09:08:52274 }
275 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Sebastian Jansson35cf9e72019-10-04 07:30:32276 channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 09:08:52277 }
ossu20a4b3f2017-04-27 09:08:52278
Benjamin Wright84583f62018-10-04 21:22:34279 // Enable the frame encryptor if a new frame encryptor has been provided.
280 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Sebastian Jansson35cf9e72019-10-04 07:30:32281 channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 21:22:34282 }
283
Johannes Kron9190b822018-10-29 10:22:05284 if (first_time ||
285 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Sebastian Jansson35cf9e72019-10-04 07:30:32286 channel_send_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 10:22:05287 }
288
Alex Narestcedd3512017-12-07 19:54:55289 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
290 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
Yves Gerey17048012019-07-26 15:49:52291
Sebastian Jansson35cf9e72019-10-04 07:30:32292 config_cs_.Leave();
Yves Gerey17048012019-07-26 15:49:52293
ossu20a4b3f2017-04-27 09:08:52294 // Audio level indication
295 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Sebastian Jansson35cf9e72019-10-04 07:30:32296 channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
297 new_ids.audio_level);
ossu20a4b3f2017-04-27 09:08:52298 }
Sebastian Jansson71c6b562019-08-14 09:31:02299
300 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
Sebastian Jansson35cf9e72019-10-04 07:30:32301 channel_send_->GetRtpRtcp()->DeregisterSendRtpHeaderExtension(
Sebastian Jansson71c6b562019-08-14 09:31:02302 kRtpExtensionAbsoluteSendTime);
303 if (new_ids.abs_send_time) {
Sebastian Jansson35cf9e72019-10-04 07:30:32304 channel_send_->GetRtpRtcp()->RegisterSendRtpHeaderExtension(
Sebastian Jansson71c6b562019-08-14 09:31:02305 kRtpExtensionAbsoluteSendTime, new_ids.abs_send_time);
306 }
307 }
308
Sebastian Jansson8d9c5402017-11-15 16:22:16309 bool transport_seq_num_id_changed =
310 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson35cf9e72019-10-04 07:30:32311 if (first_time ||
312 (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
ossu1129df22017-06-30 08:38:56313 if (!first_time) {
Sebastian Jansson35cf9e72019-10-04 07:30:32314 channel_send_->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 09:08:52315 }
316
Sebastian Jansson8d9c5402017-11-15 16:22:16317 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 11:37:49318
Sebastian Jansson35cf9e72019-10-04 07:30:32319 if (audio_send_side_bwe_ && !allocate_audio_without_feedback_ &&
Sebastian Janssonf23131f2019-10-03 08:03:55320 new_ids.transport_sequence_number != 0) {
Sebastian Jansson35cf9e72019-10-04 07:30:32321 channel_send_->EnableSendTransportSequenceNumber(
ossu20a4b3f2017-04-27 09:08:52322 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 16:22:16323 // Probing in application limited region is only used in combination with
324 // send side congestion control, wich depends on feedback packets which
325 // requires transport sequence numbers to be enabled.
Sebastian Jansson35cf9e72019-10-04 07:30:32326 if (rtp_transport_) {
Christoffer Rodbroa3522482019-05-23 10:12:48327 // Optionally request ALR probing but do not override any existing
328 // request from other streams.
Sebastian Jansson35cf9e72019-10-04 07:30:32329 if (enable_audio_alr_probing_) {
330 rtp_transport_->EnablePeriodicAlrProbing(true);
Christoffer Rodbroa3522482019-05-23 10:12:48331 }
Sebastian Jansson35cf9e72019-10-04 07:30:32332 bandwidth_observer = rtp_transport_->GetBandwidthObserver();
Niels Möller7d76a312018-10-26 10:57:07333 }
ossu20a4b3f2017-04-27 09:08:52334 }
Sebastian Jansson35cf9e72019-10-04 07:30:32335 if (rtp_transport_) {
336 channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
337 bandwidth_observer);
Niels Möller7d76a312018-10-26 10:57:07338 }
ossu20a4b3f2017-04-27 09:08:52339 }
Sebastian Jansson35cf9e72019-10-04 07:30:32340 config_cs_.Enter();
Steve Antonbb50ce52018-03-26 17:24:32341 // MID RTP header extension.
Steve Anton003930a2018-03-29 19:37:21342 if ((first_time || new_ids.mid != old_ids.mid ||
343 new_config.rtp.mid != old_config.rtp.mid) &&
344 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Sebastian Jansson35cf9e72019-10-04 07:30:32345 channel_send_->SetMid(new_config.rtp.mid, new_ids.mid);
Steve Antonbb50ce52018-03-26 17:24:32346 }
347
Amit Hilbuch77938e62018-12-21 17:23:38348 // RID RTP header extension
349 if ((first_time || new_ids.rid != old_ids.rid ||
350 new_ids.repaired_rid != old_ids.repaired_rid ||
351 new_config.rtp.rid != old_config.rtp.rid)) {
Sebastian Jansson35cf9e72019-10-04 07:30:32352 channel_send_->SetRid(new_config.rtp.rid, new_ids.rid,
353 new_ids.repaired_rid);
Amit Hilbuch77938e62018-12-21 17:23:38354 }
355
Sebastian Jansson35cf9e72019-10-04 07:30:32356 if (!ReconfigureSendCodec(new_config)) {
Mirko Bonadei675513b2017-11-09 10:09:25357 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 09:08:52358 }
359
Sebastian Jansson35cf9e72019-10-04 07:30:32360 if (sending_) {
361 ReconfigureBitrateObserver(new_config);
Oskar Sundbomf85e31b2017-12-20 15:38:09362 }
Sebastian Jansson35cf9e72019-10-04 07:30:32363 config_ = new_config;
364 config_cs_.Leave();
ossu20a4b3f2017-04-27 09:08:52365}
366
solenberg3a941542015-11-16 15:34:50367void AudioSendStream::Start() {
Sebastian Jansson8672cac2019-03-01 14:57:55368 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenberg2a877972017-12-15 15:42:15369 if (sending_) {
370 return;
371 }
Sebastian Janssonf23131f2019-10-03 08:03:55372 // TODO(srte): We should not add audio to allocation just because
373 // audio_send_side_bwe_ is false.
374 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
375 config_.max_bitrate_bps != -1 &&
376 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0 ||
377 !audio_send_side_bwe_)) {
Erik Språngaa59eca2019-07-24 12:52:55378 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Janssonb6863962018-10-10 08:23:13379 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Sebastian Jansson8672cac2019-03-01 14:57:55380 rtc::Event thread_sync_event;
381 worker_queue_->PostTask([&] {
382 RTC_DCHECK_RUN_ON(worker_queue_);
383 ConfigureBitrateObserver();
384 thread_sync_event.Set();
385 });
386 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Janssonb6863962018-10-10 08:23:13387 } else {
388 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 11:44:06389 }
Niels Möllerdced9f62018-11-19 09:27:07390 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 15:42:15391 sending_ = true;
392 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
393 encoder_num_channels_);
solenberg3a941542015-11-16 15:34:50394}
395
396void AudioSendStream::Stop() {
Sebastian Janssonc01367d2019-04-08 13:20:44397 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 15:42:15398 if (!sending_) {
399 return;
400 }
401
ossu20a4b3f2017-04-27 09:08:52402 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 09:27:07403 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 15:42:15404 sending_ = false;
405 audio_state()->RemoveSendingStream(this);
406}
407
408void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
409 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Henrik Boströmd2c336f2019-07-03 15:11:10410 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
411 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
412 audio_frame->sample_rate_hz_;
413 {
414 // Note: SendAudioData() passes the frame further down the pipeline and it
415 // may eventually get sent. But this method is invoked even if we are not
416 // connected, as long as we have an AudioSendStream (created as a result of
417 // an O/A exchange). This means that we are calculating audio levels whether
418 // or not we are sending samples.
419 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
420 // should move from send-streams to the local audio sources or tracks; a
421 // send-stream should not be required to read the microphone audio levels.
422 rtc::CritScope cs(&audio_level_lock_);
423 audio_level_.ComputeLevel(*audio_frame, duration);
424 }
Niels Möllerdced9f62018-11-19 09:27:07425 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 15:34:50426}
427
solenbergffbbcac2016-11-17 13:25:37428bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 13:03:05429 int payload_frequency,
430 int event,
solenberg8842c3e2016-03-11 11:06:41431 int duration_ms) {
Sebastian Janssonc01367d2019-04-08 13:20:44432 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 13:29:42433 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
434 payload_frequency);
435 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 14:22:19436}
437
solenberg94218532016-06-16 17:53:22438void AudioSendStream::SetMuted(bool muted) {
Sebastian Janssonc01367d2019-04-08 13:20:44439 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerdced9f62018-11-19 09:27:07440 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 17:53:22441}
442
solenbergc7a8b082015-10-16 21:35:07443webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d460902017-11-24 16:29:59444 return GetStats(true);
445}
446
447webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
448 bool has_remote_tracks) const {
Sebastian Janssonc01367d2019-04-08 13:20:44449 RTC_DCHECK(worker_thread_checker_.IsCurrent());
solenberg85a04962015-10-27 10:35:21450 webrtc::AudioSendStream::Stats stats;
451 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 09:27:07452 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 10:35:21453
Niels Möllerdced9f62018-11-19 09:27:07454 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
solenberg85a04962015-10-27 10:35:21455 stats.bytes_sent = call_stats.bytesSent;
Henrik Boströmcf96e0f2019-04-17 11:51:53456 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
solenberg85a04962015-10-27 10:35:21457 stats.packets_sent = call_stats.packetsSent;
Henrik Boströmcf96e0f2019-04-17 11:51:53458 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
solenberg8b85de22015-11-16 17:48:04459 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
460 // returns 0 to indicate an error value.
461 if (call_stats.rttMs > 0) {
462 stats.rtt_ms = call_stats.rttMs;
463 }
ossu20a4b3f2017-04-27 09:08:52464 if (config_.send_codec_spec) {
465 const auto& spec = *config_.send_codec_spec;
466 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 09:57:35467 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 10:35:21468
469 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 09:27:07470 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 17:48:04471 // Lookup report for send ssrc only.
472 if (block.source_SSRC == stats.local_ssrc) {
473 stats.packets_lost = block.cumulative_num_packets_lost;
474 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
ossu20a4b3f2017-04-27 09:08:52475 // Convert timestamps to milliseconds.
476 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 17:48:04477 stats.jitter_ms =
ossu20a4b3f2017-04-27 09:08:52478 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 10:35:21479 }
solenberg8b85de22015-11-16 17:48:04480 break;
solenberg85a04962015-10-27 10:35:21481 }
482 }
483 }
484
Henrik Boströmd2c336f2019-07-03 15:11:10485 {
486 rtc::CritScope cs(&audio_level_lock_);
487 stats.audio_level = audio_level_.LevelFullRange();
488 stats.total_input_energy = audio_level_.TotalEnergy();
489 stats.total_input_duration = audio_level_.TotalDuration();
490 }
solenberg796b8f92017-03-02 01:02:23491
Fredrik Solenberg2a877972017-12-15 15:42:15492 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 09:27:07493 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d460902017-11-24 16:29:59494 RTC_DCHECK(audio_state_->audio_processing());
495 stats.apm_statistics =
496 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 10:35:21497
Henrik Boström6e436d12019-05-27 10:19:33498 stats.report_block_datas = std::move(call_stats.report_block_datas);
499
solenberg85a04962015-10-27 10:35:21500 return stats;
501}
502
Niels Möller8fb1a6a2019-03-05 13:29:42503void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
pbos1ba8d392016-05-02 03:18:34504 // TODO(solenberg): Tests call this function on a network thread, libjingle
505 // calls on the worker thread. We should move towards always using a network
506 // thread. Then this check can be enabled.
Sebastian Janssonc01367d2019-04-08 13:20:44507 // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
Niels Möller8fb1a6a2019-03-05 13:29:42508 channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-02 03:18:34509}
510
Sebastian Janssonc0e4d452018-10-25 13:08:32511uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson62aee932019-10-02 10:27:06512 RTC_DCHECK_RUN_ON(worker_queue_);
Daniel Lee93562522019-05-03 12:40:13513 // Pick a target bitrate between the constraints. Overrules the allocator if
514 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
515 // higher than max to allow for e.g. extra FEC.
516 auto constraints = GetMinMaxBitrateConstraints();
517 update.target_bitrate.Clamp(constraints.min, constraints.max);
mflodman86cc6ff2016-07-26 11:44:06518
Sebastian Jansson254d8692018-11-21 18:19:00519 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 11:44:06520
521 // The amount of audio protection is not exposed by the encoder, hence
522 // always returning 0.
523 return 0;
524}
525
elad.alond12a8e12017-03-23 18:04:48526void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
Sebastian Janssonc01367d2019-04-08 13:20:44527 RTC_DCHECK(pacer_thread_checker_.IsCurrent());
elad.alond12a8e12017-03-23 18:04:48528 // Only packets that belong to this stream are of interest.
Yves Gerey17048012019-07-26 15:49:52529 bool same_ssrc;
530 {
531 rtc::CritScope lock(&config_cs_);
532 same_ssrc = ssrc == config_.rtp.ssrc;
533 }
534 if (same_ssrc) {
elad.alond12a8e12017-03-23 18:04:48535 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 07:15:35536 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 18:04:48537 // setting both PLR and RPLR to unknown. Consider (during upcoming
538 // refactoring) passing an indication of such an event.
Sebastian Jansson977b3352019-03-04 16:43:34539 packet_loss_tracker_.OnPacketAdded(seq_num, clock_->TimeInMilliseconds());
elad.alond12a8e12017-03-23 18:04:48540 }
541}
542
543void AudioSendStream::OnPacketFeedbackVector(
544 const std::vector<PacketFeedback>& packet_feedback_vector) {
Sebastian Janssonc01367d2019-04-08 13:20:44545 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Danil Chapovalovb9b146c2018-06-15 10:28:07546 absl::optional<float> plr;
547 absl::optional<float> rplr;
elad.alond12a8e12017-03-23 18:04:48548 {
549 rtc::CritScope lock(&packet_loss_tracker_cs_);
550 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
551 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 22:29:50552 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 18:04:48553 }
eladalonedd6eea2017-05-25 07:15:35554 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 18:04:48555 // the previously sent value is no longer relevant. This will be taken care
556 // of with some refactoring which is now being done.
557 if (plr) {
Niels Möllerdced9f62018-11-19 09:27:07558 channel_send_->OnTwccBasedUplinkPacketLossRate(*plr);
elad.alond12a8e12017-03-23 18:04:48559 }
elad.alondadb4dc2017-03-23 22:29:50560 if (rplr) {
Niels Möllerdced9f62018-11-19 09:27:07561 channel_send_->OnRecoverableUplinkPacketLossRate(*rplr);
elad.alondadb4dc2017-03-23 22:29:50562 }
elad.alond12a8e12017-03-23 18:04:48563}
564
Anton Sukhanov626015d2019-02-04 23:16:06565void AudioSendStream::SetTransportOverhead(
566 int transport_overhead_per_packet_bytes) {
Sebastian Janssonc01367d2019-04-08 13:20:44567 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Anton Sukhanov626015d2019-02-04 23:16:06568 rtc::CritScope cs(&overhead_per_packet_lock_);
569 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
570 UpdateOverheadForEncoder();
571}
572
573void AudioSendStream::OnOverheadChanged(
574 size_t overhead_bytes_per_packet_bytes) {
575 rtc::CritScope cs(&overhead_per_packet_lock_);
576 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
577 UpdateOverheadForEncoder();
578}
579
580void AudioSendStream::UpdateOverheadForEncoder() {
581 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
Bjorn A Mellem413ccc42019-04-26 22:41:05582 if (overhead_per_packet_bytes == 0) {
583 return; // Overhead is not known yet, do not tell the encoder.
584 }
Sebastian Jansson14a7cf92019-02-13 14:11:42585 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
586 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
Anton Sukhanov626015d2019-02-04 23:16:06587 });
Sebastian Jansson8672cac2019-03-01 14:57:55588 worker_queue_->PostTask([this, overhead_per_packet_bytes] {
589 RTC_DCHECK_RUN_ON(worker_queue_);
590 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
591 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
592 if (registered_with_allocator_) {
593 ConfigureBitrateObserver();
594 }
595 }
596 });
Anton Sukhanov626015d2019-02-04 23:16:06597}
598
599size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
600 rtc::CritScope cs(&overhead_per_packet_lock_);
601 return GetPerPacketOverheadBytes();
602}
603
604size_t AudioSendStream::GetPerPacketOverheadBytes() const {
605 return transport_overhead_per_packet_bytes_ +
606 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 10:50:09607}
608
ossuc3d4b482017-05-23 13:07:11609RtpState AudioSendStream::GetRtpState() const {
610 return rtp_rtcp_module_->GetRtpState();
611}
612
Niels Möllerdced9f62018-11-19 09:27:07613const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
614 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 12:52:30615}
616
Fredrik Solenberg2a877972017-12-15 15:42:15617internal::AudioState* AudioSendStream::audio_state() {
618 internal::AudioState* audio_state =
619 static_cast<internal::AudioState*>(audio_state_.get());
620 RTC_DCHECK(audio_state);
621 return audio_state;
622}
623
624const internal::AudioState* AudioSendStream::audio_state() const {
625 internal::AudioState* audio_state =
626 static_cast<internal::AudioState*>(audio_state_.get());
627 RTC_DCHECK(audio_state);
628 return audio_state;
629}
630
Fredrik Solenberg2a877972017-12-15 15:42:15631void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
632 size_t num_channels) {
Sebastian Janssonc01367d2019-04-08 13:20:44633 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenberg2a877972017-12-15 15:42:15634 encoder_sample_rate_hz_ = sample_rate_hz;
635 encoder_num_channels_ = num_channels;
636 if (sending_) {
637 // Update AudioState's information about the stream.
638 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
639 }
640}
641
minyue7a973442016-10-20 10:27:12642// Apply current codec settings to a single voe::Channel used for sending.
Sebastian Jansson35cf9e72019-10-04 07:30:32643bool AudioSendStream::SetupSendCodec(const Config& new_config) {
ossu20a4b3f2017-04-27 09:08:52644 RTC_DCHECK(new_config.send_codec_spec);
645 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 11:06:11646
647 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 09:08:52648 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 14:18:42649 new_config.encoder_factory->MakeAudioEncoder(
650 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 10:27:12651
ossu20a4b3f2017-04-27 09:08:52652 if (!encoder) {
Jonas Olssonabbe8412018-04-03 11:40:05653 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
654 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 09:08:52655 return false;
656 }
Alex Narestbbbe4e12018-07-13 08:32:58657
ossu20a4b3f2017-04-27 09:08:52658 // If a bitrate has been specified for the codec, use it over the
659 // codec's default.
Christoffer Rodbro110c64b2019-03-06 08:51:08660 if (spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 09:08:52661 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 10:27:12662 }
663
ossu20a4b3f2017-04-27 09:08:52664 // Enable ANA if configured (currently only used by Opus).
665 if (new_config.audio_network_adaptor_config) {
666 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 07:30:32667 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 09:14:29668 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
669 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 09:08:52670 } else {
671 RTC_NOTREACHED();
minyue6b825df2016-10-31 11:08:32672 }
minyue7a973442016-10-20 10:27:12673 }
674
ossu20a4b3f2017-04-27 09:08:52675 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
676 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 10:13:44677 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 09:08:52678 cng_config.num_channels = encoder->NumChannels();
679 cng_config.payload_type = *spec.cng_payload_type;
680 cng_config.speech_encoder = std::move(encoder);
681 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 10:13:44682 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 15:03:42683
Sebastian Jansson35cf9e72019-10-04 07:30:32684 RegisterCngPayloadType(*spec.cng_payload_type,
685 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 10:27:12686 }
ossu20a4b3f2017-04-27 09:08:52687
Anton Sukhanov626015d2019-02-04 23:16:06688 // Set currently known overhead (used in ANA, opus only).
689 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
690 {
Sebastian Jansson35cf9e72019-10-04 07:30:32691 rtc::CritScope cs(&overhead_per_packet_lock_);
692 if (GetPerPacketOverheadBytes() > 0) {
693 encoder->OnReceivedOverhead(GetPerPacketOverheadBytes());
Bjorn A Mellem413ccc42019-04-26 22:41:05694 }
Anton Sukhanov626015d2019-02-04 23:16:06695 }
Sebastian Jansson35cf9e72019-10-04 07:30:32696 worker_queue_->PostTask(
697 [this, length_range = encoder->GetFrameLengthRange()] {
698 RTC_DCHECK_RUN_ON(worker_queue_);
699 frame_length_range_ = length_range;
Sebastian Jansson62aee932019-10-02 10:27:06700 });
Anton Sukhanov626015d2019-02-04 23:16:06701
Sebastian Jansson35cf9e72019-10-04 07:30:32702 StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
703 channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
704 std::move(encoder));
Anton Sukhanov626015d2019-02-04 23:16:06705
minyue7a973442016-10-20 10:27:12706 return true;
707}
708
Sebastian Jansson35cf9e72019-10-04 07:30:32709bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
710 const auto& old_config = config_;
minyue-webrtc8de18262017-07-26 12:18:40711
712 if (!new_config.send_codec_spec) {
713 // We cannot de-configure a send codec. So we will do nothing.
714 // By design, the send codec should have not been configured.
715 RTC_DCHECK(!old_config.send_codec_spec);
716 return true;
717 }
718
719 if (new_config.send_codec_spec == old_config.send_codec_spec &&
720 new_config.audio_network_adaptor_config ==
721 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 09:08:52722 return true;
723 }
724
725 // If we have no encoder, or the format or payload type's changed, create a
726 // new encoder.
727 if (!old_config.send_codec_spec ||
728 new_config.send_codec_spec->format !=
729 old_config.send_codec_spec->format ||
730 new_config.send_codec_spec->payload_type !=
731 old_config.send_codec_spec->payload_type) {
Sebastian Jansson35cf9e72019-10-04 07:30:32732 return SetupSendCodec(new_config);
ossu20a4b3f2017-04-27 09:08:52733 }
734
Danil Chapovalovb9b146c2018-06-15 10:28:07735 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 09:08:52736 new_config.send_codec_spec->target_bitrate_bps;
737 // If a bitrate has been specified for the codec, use it over the
738 // codec's default.
Christoffer Rodbro110c64b2019-03-06 08:51:08739 if (new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 09:08:52740 new_target_bitrate_bps !=
741 old_config.send_codec_spec->target_bitrate_bps) {
Sebastian Jansson35cf9e72019-10-04 07:30:32742 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 09:08:52743 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
744 });
745 }
746
Sebastian Jansson35cf9e72019-10-04 07:30:32747 ReconfigureANA(new_config);
748 ReconfigureCNG(new_config);
ossu20a4b3f2017-04-27 09:08:52749
Anton Sukhanov626015d2019-02-04 23:16:06750 // Set currently known overhead (used in ANA, opus only).
751 {
Sebastian Jansson35cf9e72019-10-04 07:30:32752 rtc::CritScope cs(&overhead_per_packet_lock_);
753 UpdateOverheadForEncoder();
Anton Sukhanov626015d2019-02-04 23:16:06754 }
755
ossu20a4b3f2017-04-27 09:08:52756 return true;
757}
758
Sebastian Jansson35cf9e72019-10-04 07:30:32759void AudioSendStream::ReconfigureANA(const Config& new_config) {
ossu20a4b3f2017-04-27 09:08:52760 if (new_config.audio_network_adaptor_config ==
Sebastian Jansson35cf9e72019-10-04 07:30:32761 config_.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 09:08:52762 return;
763 }
764 if (new_config.audio_network_adaptor_config) {
Sebastian Jansson35cf9e72019-10-04 07:30:32765 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 09:08:52766 if (encoder->EnableAudioNetworkAdaptor(
Sebastian Jansson35cf9e72019-10-04 07:30:32767 *new_config.audio_network_adaptor_config, event_log_)) {
Jonas Olsson24ea8222018-01-25 09:14:29768 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
769 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 09:08:52770 } else {
771 RTC_NOTREACHED();
772 }
773 });
774 } else {
Sebastian Jansson35cf9e72019-10-04 07:30:32775 channel_send_->CallEncoder(
Sebastian Jansson14a7cf92019-02-13 14:11:42776 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
Jonas Olsson24ea8222018-01-25 09:14:29777 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
778 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 09:08:52779 }
780}
781
Sebastian Jansson35cf9e72019-10-04 07:30:32782void AudioSendStream::ReconfigureCNG(const Config& new_config) {
ossu20a4b3f2017-04-27 09:08:52783 if (new_config.send_codec_spec->cng_payload_type ==
Sebastian Jansson35cf9e72019-10-04 07:30:32784 config_.send_codec_spec->cng_payload_type) {
ossu20a4b3f2017-04-27 09:08:52785 return;
786 }
787
ossu3b9ff382017-04-27 15:03:42788 // Register the CNG payload type if it's been added, don't do anything if CNG
789 // is removed. Payload types must not be redefined.
790 if (new_config.send_codec_spec->cng_payload_type) {
Sebastian Jansson35cf9e72019-10-04 07:30:32791 RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
792 new_config.send_codec_spec->format.clockrate_hz);
ossu3b9ff382017-04-27 15:03:42793 }
794
ossu20a4b3f2017-04-27 09:08:52795 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Sebastian Jansson35cf9e72019-10-04 07:30:32796 channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
797 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
798 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
799 if (!sub_encoders.empty()) {
800 // Replace enc with its sub encoder. We need to put the sub
801 // encoder in a temporary first, since otherwise the old value
802 // of enc would be destroyed before the new value got assigned,
803 // which would be bad since the new value is a part of the old
804 // value.
805 auto tmp = std::move(sub_encoders[0]);
806 old_encoder = std::move(tmp);
807 }
808 if (new_config.send_codec_spec->cng_payload_type) {
809 AudioEncoderCngConfig config;
810 config.speech_encoder = std::move(old_encoder);
811 config.num_channels = config.speech_encoder->NumChannels();
812 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
813 config.vad_mode = Vad::kVadNormal;
814 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
815 } else {
816 *encoder_ptr = std::move(old_encoder);
817 }
818 });
ossu20a4b3f2017-04-27 09:08:52819}
820
821void AudioSendStream::ReconfigureBitrateObserver(
ossu20a4b3f2017-04-27 09:08:52822 const webrtc::AudioSendStream::Config& new_config) {
Sebastian Jansson35cf9e72019-10-04 07:30:32823 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
ossu20a4b3f2017-04-27 09:08:52824 // Since the Config's default is for both of these to be -1, this test will
825 // allow us to configure the bitrate observer if the new config has bitrate
826 // limits set, but would only have us call RemoveBitrateObserver if we were
827 // previously configured with bitrate limits.
Sebastian Jansson35cf9e72019-10-04 07:30:32828 if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
829 config_.max_bitrate_bps == new_config.max_bitrate_bps &&
830 config_.bitrate_priority == new_config.bitrate_priority &&
831 (TransportSeqNumId(config_) == TransportSeqNumId(new_config) ||
832 !audio_send_side_bwe_)) {
ossu20a4b3f2017-04-27 09:08:52833 return;
834 }
835
Sebastian Janssonf23131f2019-10-03 08:03:55836 // TODO(srte): We should not add audio to allocation just because
837 // audio_send_side_bwe_ is false.
838 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
839 new_config.max_bitrate_bps != -1 &&
Sebastian Jansson35cf9e72019-10-04 07:30:32840 (TransportSeqNumId(new_config) != 0 || !audio_send_side_bwe_)) {
841 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
Sebastian Jansson8672cac2019-03-01 14:57:55842 rtc::Event thread_sync_event;
Sebastian Jansson35cf9e72019-10-04 07:30:32843 worker_queue_->PostTask([&] {
844 RTC_DCHECK_RUN_ON(worker_queue_);
845 registered_with_allocator_ = true;
Sebastian Jansson8672cac2019-03-01 14:57:55846 // We may get a callback immediately as the observer is registered, so
847 // make
848 // sure the bitrate limits in config_ are up-to-date.
Sebastian Jansson35cf9e72019-10-04 07:30:32849 config_.min_bitrate_bps = new_config.min_bitrate_bps;
850 config_.max_bitrate_bps = new_config.max_bitrate_bps;
851
852 config_.bitrate_priority = new_config.bitrate_priority;
853 ConfigureBitrateObserver();
Sebastian Jansson8672cac2019-03-01 14:57:55854 thread_sync_event.Set();
855 });
856 thread_sync_event.Wait(rtc::Event::kForever);
Sebastian Jansson35cf9e72019-10-04 07:30:32857 rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 09:08:52858 } else {
Sebastian Jansson35cf9e72019-10-04 07:30:32859 rtp_transport_->AccountForAudioPacketsInPacedSender(false);
860 RemoveBitrateObserver();
861 rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 09:08:52862 }
863}
864
Sebastian Jansson8672cac2019-03-01 14:57:55865void AudioSendStream::ConfigureBitrateObserver() {
866 // This either updates the current observer or adds a new observer.
867 // TODO(srte): Add overhead compensation here.
Daniel Lee93562522019-05-03 12:40:13868 auto constraints = GetMinMaxBitrateConstraints();
869
Sebastian Jansson0429f782019-10-03 16:32:45870 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
Sebastian Janssonf23131f2019-10-03 08:03:55871 if (send_side_bwe_with_overhead_) {
Sebastian Jansson0429f782019-10-03 16:32:45872 if (use_legacy_overhead_calculation_) {
873 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
874 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
875 const TimeDelta kMinPacketDuration = TimeDelta::ms(20);
876 DataRate max_overhead =
877 DataSize::bytes(kOverheadPerPacket) / kMinPacketDuration;
878 priority_bitrate += max_overhead;
879 } else {
880 RTC_DCHECK(frame_length_range_);
881 const DataSize kOverheadPerPacket =
882 DataSize::bytes(total_packet_overhead_bytes_);
883 DataRate max_overhead = kOverheadPerPacket / frame_length_range_->first;
884 priority_bitrate += max_overhead;
885 }
Sebastian Janssonf23131f2019-10-03 08:03:55886 }
Sebastian Janssonf23131f2019-10-03 08:03:55887 if (allocation_settings_.priority_bitrate_raw)
888 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
889
Sebastian Jansson8672cac2019-03-01 14:57:55890 bitrate_allocator_->AddObserver(
Daniel Lee93562522019-05-03 12:40:13891 this,
892 MediaStreamAllocationConfig{
893 constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
Sebastian Janssonf23131f2019-10-03 08:03:55894 priority_bitrate.bps(), true,
895 allocation_settings_.bitrate_priority.value_or(
Jonas Olsson8f119ca2019-05-08 08:56:23896 config_.bitrate_priority)});
ossu20a4b3f2017-04-27 09:08:52897}
898
899void AudioSendStream::RemoveBitrateObserver() {
Sebastian Janssonc01367d2019-04-08 13:20:44900 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllerc572ff32018-11-07 07:43:50901 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 09:08:52902 worker_queue_->PostTask([this, &thread_sync_event] {
Sebastian Jansson8672cac2019-03-01 14:57:55903 RTC_DCHECK_RUN_ON(worker_queue_);
904 registered_with_allocator_ = false;
ossu20a4b3f2017-04-27 09:08:52905 bitrate_allocator_->RemoveObserver(this);
906 thread_sync_event.Set();
907 });
908 thread_sync_event.Wait(rtc::Event::kForever);
909}
910
Daniel Lee93562522019-05-03 12:40:13911AudioSendStream::TargetAudioBitrateConstraints
912AudioSendStream::GetMinMaxBitrateConstraints() const {
913 TargetAudioBitrateConstraints constraints{
914 DataRate::bps(config_.min_bitrate_bps),
915 DataRate::bps(config_.max_bitrate_bps)};
916
917 // If bitrates were explicitly overriden via field trial, use those values.
Sebastian Janssonf23131f2019-10-03 08:03:55918 if (allocation_settings_.min_bitrate)
919 constraints.min = *allocation_settings_.min_bitrate;
920 if (allocation_settings_.max_bitrate)
921 constraints.max = *allocation_settings_.max_bitrate;
Daniel Lee93562522019-05-03 12:40:13922
Sebastian Jansson62aee932019-10-02 10:27:06923 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
924 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
925 RTC_DCHECK_GE(constraints.max, constraints.min);
Sebastian Janssonf23131f2019-10-03 08:03:55926 if (send_side_bwe_with_overhead_) {
Sebastian Jansson62aee932019-10-02 10:27:06927 if (use_legacy_overhead_calculation_) {
928 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
929 const DataSize kOverheadPerPacket = DataSize::bytes(20 + 8 + 10 + 12);
930 const TimeDelta kMaxFrameLength =
931 TimeDelta::ms(60); // Based on Opus spec
932 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
933 constraints.min += kMinOverhead;
934 constraints.max += kMinOverhead;
935 } else {
936 RTC_DCHECK(frame_length_range_);
937 const DataSize kOverheadPerPacket =
938 DataSize::bytes(total_packet_overhead_bytes_);
939 constraints.min += kOverheadPerPacket / frame_length_range_->second;
940 constraints.max += kOverheadPerPacket / frame_length_range_->first;
941 }
Daniel Lee93562522019-05-03 12:40:13942 }
943 return constraints;
944}
945
ossu3b9ff382017-04-27 15:03:42946void AudioSendStream::RegisterCngPayloadType(int payload_type,
947 int clockrate_hz) {
Niels Mölleree5ccbc2019-03-06 15:47:29948 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
ossu3b9ff382017-04-27 15:03:42949}
solenbergc7a8b082015-10-16 21:35:07950} // namespace internal
951} // namespace webrtc