blob: 3e97ab23ecc75e9496b24234c6963d0b0690a83c [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
13#include <string>
ossu20a4b3f2017-04-27 02:08:52 -070014#include <utility>
15#include <vector>
solenbergc7a8b082015-10-16 14:35:07 -070016
Niels Möllerfa4e1852018-08-14 09:43:34 +020017#include "absl/memory/memory.h"
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"
22#include "api/crypto/frameencryptorinterface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "audio/audio_state.h"
Yves Gerey988cc082018-10-23 12:03:01 +020024#include "audio/channel_send.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "audio/conversion.h"
Yves Gerey988cc082018-10-23 12:03:01 +020026#include "call/rtp_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "common_audio/vad/include/vad.h"
29#include "common_types.h" // NOLINT(build/include)
Oskar Sundbom56ef3052018-10-30 16:11:02 +010030#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
31#include "logging/rtc_event_log/rtc_event_log.h"
32#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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/checks.h"
36#include "rtc_base/event.h"
37#include "rtc_base/function_view.h"
38#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"
41#include "rtc_base/timeutils.h"
Alex Narestcedd3512017-12-07 20:54:55 +010042#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070043
44namespace webrtc {
solenbergc7a8b082015-10-16 14:35:07 -070045namespace internal {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010046namespace {
eladalonedd6eea2017-05-25 00:15:35 -070047// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070048constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
49constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
50constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
51
Niels Möllerdced9f62018-11-19 10:27:07 +010052void CallEncoder(const std::unique_ptr<voe::ChannelSendInterface>& channel_send,
ossu20a4b3f2017-04-27 02:08:52 -070053 rtc::FunctionView<void(AudioEncoder*)> lambda) {
Niels Möllerdced9f62018-11-19 10:27:07 +010054 channel_send->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
ossu20a4b3f2017-04-27 02:08:52 -070055 RTC_DCHECK(encoder_ptr);
56 lambda(encoder_ptr->get());
57 });
58}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010059
Oskar Sundbom56ef3052018-10-30 16:11:02 +010060void UpdateEventLogStreamConfig(RtcEventLog* event_log,
61 const AudioSendStream::Config& config,
62 const AudioSendStream::Config* old_config) {
63 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
64 // Only update if any of the things we log have changed.
65 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
66 const absl::optional<SendCodecSpec>& b) {
67 if (a.has_value() && b.has_value()) {
68 return a->format.name == b->format.name &&
69 a->payload_type == b->payload_type;
70 }
71 return !a.has_value() && !b.has_value();
72 };
73
74 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
75 config.rtp.extensions == old_config->rtp.extensions &&
76 payload_types_equal(config.send_codec_spec,
77 old_config->send_codec_spec)) {
78 return;
79 }
80
81 auto rtclog_config = absl::make_unique<rtclog::StreamConfig>();
82 rtclog_config->local_ssrc = config.rtp.ssrc;
83 rtclog_config->rtp_extensions = config.rtp.extensions;
84 if (config.send_codec_spec) {
85 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
86 config.send_codec_spec->payload_type, 0);
87 }
88 event_log->Log(absl::make_unique<RtcEventAudioSendStreamConfig>(
89 std::move(rtclog_config)));
90}
91
ossu20a4b3f2017-04-27 02:08:52 -070092} // namespace
93
Sam Zackrisson06953ba2018-02-01 16:53:16 +010094// Helper class to track the actively sending lifetime of this stream.
sazac58f8c02017-07-19 00:39:19 -070095class AudioSendStream::TimedTransport : public Transport {
96 public:
97 TimedTransport(Transport* transport, TimeInterval* time_interval)
98 : transport_(transport), lifetime_(time_interval) {}
99 bool SendRtp(const uint8_t* packet,
100 size_t length,
101 const PacketOptions& options) {
102 if (lifetime_) {
103 lifetime_->Extend();
104 }
105 return transport_->SendRtp(packet, length, options);
106 }
107 bool SendRtcp(const uint8_t* packet, size_t length) {
108 return transport_->SendRtcp(packet, length);
109 }
110 ~TimedTransport() {}
111
112 private:
113 Transport* transport_;
114 TimeInterval* lifetime_;
115};
116
solenberg566ef242015-11-06 15:34:49 -0800117AudioSendStream::AudioSendStream(
118 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100119 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -0700120 rtc::TaskQueue* worker_queue,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100121 ProcessThread* module_process_thread,
Niels Möller7d76a312018-10-26 12:57:07 +0200122 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200123 BitrateAllocatorInterface* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -0800124 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -0700125 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200126 const absl::optional<RtpState>& suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100127 TimeInterval* overall_call_lifetime)
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100128 : AudioSendStream(config,
129 audio_state,
130 worker_queue,
Niels Möller7d76a312018-10-26 12:57:07 +0200131 rtp_transport,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100132 bitrate_allocator,
133 event_log,
134 rtcp_rtt_stats,
135 suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100136 overall_call_lifetime,
Niels Möllerdced9f62018-11-19 10:27:07 +0100137 voe::CreateChannelSend(worker_queue,
138 module_process_thread,
139 config.media_transport,
140 rtcp_rtt_stats,
141 event_log,
142 config.frame_encryptor,
143 config.crypto_options,
144 config.rtp.extmap_allow_mixed,
145 config.rtcp_report_interval_ms)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100146
147AudioSendStream::AudioSendStream(
148 const webrtc::AudioSendStream::Config& config,
149 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
150 rtc::TaskQueue* worker_queue,
Niels Möller7d76a312018-10-26 12:57:07 +0200151 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200152 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100153 RtcEventLog* event_log,
154 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200155 const absl::optional<RtpState>& suspended_rtp_state,
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100156 TimeInterval* overall_call_lifetime,
Niels Möllerdced9f62018-11-19 10:27:07 +0100157 std::unique_ptr<voe::ChannelSendInterface> channel_send)
perkj26091b12016-09-01 01:17:40 -0700158 : worker_queue_(worker_queue),
Niels Möller7d76a312018-10-26 12:57:07 +0200159 config_(Config(/*send_transport=*/nullptr,
160 /*media_transport=*/nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700161 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 10:27:07 +0100162 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 02:08:52 -0700163 event_log_(event_log),
michaeltf4caaab2017-01-16 23:55:07 -0800164 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 12:57:07 +0200165 rtp_transport_(rtp_transport),
elad.alond12a8e12017-03-23 11:04:48 -0700166 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
167 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700168 kRecoverablePacketLossRateMinNumAckedPairs),
169 rtp_rtcp_module_(nullptr),
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100170 suspended_rtp_state_(suspended_rtp_state),
171 overall_call_lifetime_(overall_call_lifetime) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100172 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100173 RTC_DCHECK(worker_queue_);
174 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100175 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100176 RTC_DCHECK(bitrate_allocator_);
Niels Möller7d76a312018-10-26 12:57:07 +0200177 // TODO(nisse): Eventually, we should have only media_transport. But for the
178 // time being, we can have either. When media transport is injected, there
179 // should be no rtp_transport, and below check should be strengthened to XOR
180 // (either rtp_transport or media_transport but not both).
181 RTC_DCHECK(rtp_transport || config.media_transport);
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100182 RTC_DCHECK(overall_call_lifetime_);
solenberg3a941542015-11-16 07:34:50 -0800183
Niels Möllerdced9f62018-11-19 10:27:07 +0100184 rtp_rtcp_module_ = channel_send_->GetRtpRtcp();
ossuc3d4b482017-05-23 06:07:11 -0700185 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700186
ossu20a4b3f2017-04-27 02:08:52 -0700187 ConfigureStream(this, config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700188
189 pacer_thread_checker_.DetachFromThread();
Niels Möller7d76a312018-10-26 12:57:07 +0200190 if (rtp_transport_) {
191 // Signal congestion controller this object is ready for OnPacket*
192 // callbacks.
193 rtp_transport_->RegisterPacketFeedbackObserver(this);
194 }
solenbergc7a8b082015-10-16 14:35:07 -0700195}
196
197AudioSendStream::~AudioSendStream() {
elad.alond12a8e12017-03-23 11:04:48 -0700198 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100199 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100200 RTC_DCHECK(!sending_);
Niels Möller7d76a312018-10-26 12:57:07 +0200201 if (rtp_transport_) {
202 rtp_transport_->DeRegisterPacketFeedbackObserver(this);
Niels Möllerdced9f62018-11-19 10:27:07 +0100203 channel_send_->RegisterTransport(nullptr);
204 channel_send_->ResetSenderCongestionControlObjects();
Niels Möller7d76a312018-10-26 12:57:07 +0200205 }
Sam Zackrisson06953ba2018-02-01 16:53:16 +0100206 // Lifetime can only be updated after deregistering
207 // |timed_send_transport_adapter_| in the underlying channel object to avoid
208 // data races in |active_lifetime_|.
209 overall_call_lifetime_->Extend(active_lifetime_);
solenbergc7a8b082015-10-16 14:35:07 -0700210}
211
eladalonabbc4302017-07-26 02:09:44 -0700212const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
213 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
214 return config_;
215}
216
ossu20a4b3f2017-04-27 02:08:52 -0700217void AudioSendStream::Reconfigure(
218 const webrtc::AudioSendStream::Config& new_config) {
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100219 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ossu20a4b3f2017-04-27 02:08:52 -0700220 ConfigureStream(this, new_config, false);
221}
222
Alex Narestcedd3512017-12-07 20:54:55 +0100223AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
224 const std::vector<RtpExtension>& extensions) {
225 ExtensionIds ids;
226 for (const auto& extension : extensions) {
227 if (extension.uri == RtpExtension::kAudioLevelUri) {
228 ids.audio_level = extension.id;
229 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
230 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 10:24:32 -0700231 } else if (extension.uri == RtpExtension::kMidUri) {
232 ids.mid = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100233 }
234 }
235 return ids;
236}
237
ossu20a4b3f2017-04-27 02:08:52 -0700238void AudioSendStream::ConfigureStream(
239 webrtc::internal::AudioSendStream* stream,
240 const webrtc::AudioSendStream::Config& new_config,
241 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100242 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
243 << new_config.ToString();
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100244 UpdateEventLogStreamConfig(stream->event_log_, new_config,
245 first_time ? nullptr : &stream->config_);
246
Niels Möllerdced9f62018-11-19 10:27:07 +0100247 const auto& channel_send = stream->channel_send_;
ossu20a4b3f2017-04-27 02:08:52 -0700248 const auto& old_config = stream->config_;
249
250 if (first_time || old_config.rtp.ssrc != new_config.rtp.ssrc) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100251 channel_send->SetLocalSSRC(new_config.rtp.ssrc);
ossuc3d4b482017-05-23 06:07:11 -0700252 if (stream->suspended_rtp_state_) {
253 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
254 }
ossu20a4b3f2017-04-27 02:08:52 -0700255 }
256 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100257 channel_send->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700258 }
259 // TODO(solenberg): Config NACK history window (which is a packet count),
260 // using the actual packet size for the configured codec.
261 if (first_time || old_config.rtp.nack.rtp_history_ms !=
262 new_config.rtp.nack.rtp_history_ms) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100263 channel_send->SetNACKStatus(new_config.rtp.nack.rtp_history_ms != 0,
264 new_config.rtp.nack.rtp_history_ms / 20);
ossu20a4b3f2017-04-27 02:08:52 -0700265 }
266
Yves Gerey665174f2018-06-19 15:03:05 +0200267 if (first_time || new_config.send_transport != old_config.send_transport) {
ossu20a4b3f2017-04-27 02:08:52 -0700268 if (old_config.send_transport) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100269 channel_send->RegisterTransport(nullptr);
ossu20a4b3f2017-04-27 02:08:52 -0700270 }
sazac58f8c02017-07-19 00:39:19 -0700271 if (new_config.send_transport) {
272 stream->timed_send_transport_adapter_.reset(new TimedTransport(
273 new_config.send_transport, &stream->active_lifetime_));
274 } else {
275 stream->timed_send_transport_adapter_.reset(nullptr);
276 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100277 channel_send->RegisterTransport(
sazac58f8c02017-07-19 00:39:19 -0700278 stream->timed_send_transport_adapter_.get());
ossu20a4b3f2017-04-27 02:08:52 -0700279 }
280
Benjamin Wright84583f62018-10-04 14:22:34 -0700281 // Enable the frame encryptor if a new frame encryptor has been provided.
282 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100283 channel_send->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700284 }
285
Johannes Kron9190b822018-10-29 11:22:05 +0100286 if (first_time ||
287 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100288 channel_send->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100289 }
290
Alex Narestcedd3512017-12-07 20:54:55 +0100291 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
292 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
ossu20a4b3f2017-04-27 02:08:52 -0700293 // Audio level indication
294 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100295 channel_send->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
296 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700297 }
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100298 bool transport_seq_num_id_changed =
299 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Alex Narest867e5102018-06-12 13:40:18 +0200300 if (first_time ||
301 (transport_seq_num_id_changed &&
302 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC"))) {
ossu1129df22017-06-30 01:38:56 -0700303 if (!first_time) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100304 channel_send->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700305 }
306
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100307 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Alex Narest867e5102018-06-12 13:40:18 +0200308 bool has_transport_sequence_number =
309 new_ids.transport_sequence_number != 0 &&
310 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC");
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100311 if (has_transport_sequence_number) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100312 channel_send->EnableSendTransportSequenceNumber(
ossu20a4b3f2017-04-27 02:08:52 -0700313 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100314 // Probing in application limited region is only used in combination with
315 // send side congestion control, wich depends on feedback packets which
316 // requires transport sequence numbers to be enabled.
Niels Möller7d76a312018-10-26 12:57:07 +0200317 if (stream->rtp_transport_) {
318 stream->rtp_transport_->EnablePeriodicAlrProbing(true);
319 bandwidth_observer = stream->rtp_transport_->GetBandwidthObserver();
320 }
ossu20a4b3f2017-04-27 02:08:52 -0700321 }
Niels Möller7d76a312018-10-26 12:57:07 +0200322 if (stream->rtp_transport_) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100323 channel_send->RegisterSenderCongestionControlObjects(
Niels Möller7d76a312018-10-26 12:57:07 +0200324 stream->rtp_transport_, bandwidth_observer);
325 }
ossu20a4b3f2017-04-27 02:08:52 -0700326 }
Steve Antonbb50ce52018-03-26 10:24:32 -0700327 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700328 if ((first_time || new_ids.mid != old_ids.mid ||
329 new_config.rtp.mid != old_config.rtp.mid) &&
330 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100331 channel_send->SetMid(new_config.rtp.mid, new_ids.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700332 }
333
ossu20a4b3f2017-04-27 02:08:52 -0700334 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100335 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700336 }
337
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100338 if (stream->sending_) {
339 ReconfigureBitrateObserver(stream, new_config);
340 }
ossu20a4b3f2017-04-27 02:08:52 -0700341 stream->config_ = new_config;
342}
343
solenberg3a941542015-11-16 07:34:50 -0800344void AudioSendStream::Start() {
elad.alond12a8e12017-03-23 11:04:48 -0700345 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100346 if (sending_) {
347 return;
348 }
349
Sebastian Jansson763e9472018-03-21 12:46:56 +0100350 bool has_transport_sequence_number =
Alex Narest867e5102018-06-12 13:40:18 +0200351 FindExtensionIds(config_.rtp.extensions).transport_sequence_number != 0 &&
352 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ForceNoTWCC");
Alex Narestcedd3512017-12-07 20:54:55 +0100353 if (config_.min_bitrate_bps != -1 && config_.max_bitrate_bps != -1 &&
Tim Haloun648d28a2018-10-18 16:52:22 -0700354 !config_.has_dscp &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100355 (has_transport_sequence_number ||
Alex Narestbcf91802018-06-25 16:08:36 +0200356 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe") ||
357 webrtc::field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC"))) {
Alex Narest78609d52017-10-20 10:37:47 +0200358 // Audio BWE is enabled.
Niels Möller7d76a312018-10-26 12:57:07 +0200359 rtp_transport_->packet_sender()->SetAccountForAudioPackets(true);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200360 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Seth Hampson24722b32017-12-22 09:36:42 -0800361 ConfigureBitrateObserver(config_.min_bitrate_bps, config_.max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100362 config_.bitrate_priority,
363 has_transport_sequence_number);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200364 } else {
365 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700366 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100367 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100368 sending_ = true;
369 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
370 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800371}
372
373void AudioSendStream::Stop() {
elad.alond12a8e12017-03-23 11:04:48 -0700374 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100375 if (!sending_) {
376 return;
377 }
378
ossu20a4b3f2017-04-27 02:08:52 -0700379 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100380 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100381 sending_ = false;
382 audio_state()->RemoveSendingStream(this);
383}
384
385void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
386 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100387 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800388}
389
solenbergffbbcac2016-11-17 05:25:37 -0800390bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200391 int payload_frequency,
392 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800393 int duration_ms) {
elad.alond12a8e12017-03-23 11:04:48 -0700394 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100395 return channel_send_->SetSendTelephoneEventPayloadType(payload_type,
396 payload_frequency) &&
397 channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100398}
399
solenberg94218532016-06-16 10:53:22 -0700400void AudioSendStream::SetMuted(bool muted) {
elad.alond12a8e12017-03-23 11:04:48 -0700401 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100402 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700403}
404
solenbergc7a8b082015-10-16 14:35:07 -0700405webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100406 return GetStats(true);
407}
408
409webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
410 bool has_remote_tracks) const {
elad.alond12a8e12017-03-23 11:04:48 -0700411 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -0700412 webrtc::AudioSendStream::Stats stats;
413 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100414 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700415
Niels Möllerdced9f62018-11-19 10:27:07 +0100416 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700417 stats.bytes_sent = call_stats.bytesSent;
418 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800419 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
420 // returns 0 to indicate an error value.
421 if (call_stats.rttMs > 0) {
422 stats.rtt_ms = call_stats.rttMs;
423 }
ossu20a4b3f2017-04-27 02:08:52 -0700424 if (config_.send_codec_spec) {
425 const auto& spec = *config_.send_codec_spec;
426 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100427 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700428
429 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100430 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800431 // Lookup report for send ssrc only.
432 if (block.source_SSRC == stats.local_ssrc) {
433 stats.packets_lost = block.cumulative_num_packets_lost;
434 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
435 stats.ext_seqnum = block.extended_highest_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700436 // Convert timestamps to milliseconds.
437 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800438 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700439 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700440 }
solenberg8b85de22015-11-16 09:48:04 -0800441 break;
solenberg85a04962015-10-27 03:35:21 -0700442 }
443 }
444 }
445
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100446 AudioState::Stats input_stats = audio_state()->GetAudioInputStats();
447 stats.audio_level = input_stats.audio_level;
448 stats.total_input_energy = input_stats.total_energy;
449 stats.total_input_duration = input_stats.total_duration;
solenberg796b8f92017-03-01 17:02:23 -0800450
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100451 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100452 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100453 RTC_DCHECK(audio_state_->audio_processing());
454 stats.apm_statistics =
455 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700456
457 return stats;
458}
459
pbos1ba8d392016-05-01 20:18:34 -0700460void AudioSendStream::SignalNetworkState(NetworkState state) {
elad.alond12a8e12017-03-23 11:04:48 -0700461 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700462}
463
464bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
465 // TODO(solenberg): Tests call this function on a network thread, libjingle
466 // calls on the worker thread. We should move towards always using a network
467 // thread. Then this check can be enabled.
elad.alond12a8e12017-03-23 11:04:48 -0700468 // RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100469 return channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700470}
471
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200472uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
stefanfca900a2017-04-10 03:53:00 -0700473 // A send stream may be allocated a bitrate of zero if the allocator decides
474 // to disable it. For now we ignore this decision and keep sending on min
475 // bitrate.
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200476 if (update.bitrate_bps == 0) {
477 update.bitrate_bps = config_.min_bitrate_bps;
stefanfca900a2017-04-10 03:53:00 -0700478 }
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200479 RTC_DCHECK_GE(update.bitrate_bps,
480 static_cast<uint32_t>(config_.min_bitrate_bps));
mflodman86cc6ff2016-07-26 04:44:06 -0700481 // The bitrate allocator might allocate an higher than max configured bitrate
482 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
minyue10cbb462016-11-07 09:29:22 -0800483 const uint32_t max_bitrate_bps = config_.max_bitrate_bps;
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200484 if (update.bitrate_bps > max_bitrate_bps)
485 update.bitrate_bps = max_bitrate_bps;
mflodman86cc6ff2016-07-26 04:44:06 -0700486
Niels Möllerdced9f62018-11-19 10:27:07 +0100487 channel_send_->SetBitrate(update.bitrate_bps, update.bwe_period_ms);
mflodman86cc6ff2016-07-26 04:44:06 -0700488
489 // The amount of audio protection is not exposed by the encoder, hence
490 // always returning 0.
491 return 0;
492}
493
elad.alond12a8e12017-03-23 11:04:48 -0700494void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
495 RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread());
496 // Only packets that belong to this stream are of interest.
497 if (ssrc == config_.rtp.ssrc) {
498 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700499 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700500 // setting both PLR and RPLR to unknown. Consider (during upcoming
501 // refactoring) passing an indication of such an event.
502 packet_loss_tracker_.OnPacketAdded(seq_num, rtc::TimeMillis());
503 }
504}
505
506void AudioSendStream::OnPacketFeedbackVector(
507 const std::vector<PacketFeedback>& packet_feedback_vector) {
eladalon3651fdd2017-08-24 07:26:25 -0700508 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200509 absl::optional<float> plr;
510 absl::optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700511 {
512 rtc::CritScope lock(&packet_loss_tracker_cs_);
513 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
514 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700515 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700516 }
eladalonedd6eea2017-05-25 00:15:35 -0700517 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700518 // the previously sent value is no longer relevant. This will be taken care
519 // of with some refactoring which is now being done.
520 if (plr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100521 channel_send_->OnTwccBasedUplinkPacketLossRate(*plr);
elad.alond12a8e12017-03-23 11:04:48 -0700522 }
elad.alondadb4dc2017-03-23 15:29:50 -0700523 if (rplr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100524 channel_send_->OnRecoverableUplinkPacketLossRate(*rplr);
elad.alondadb4dc2017-03-23 15:29:50 -0700525 }
elad.alond12a8e12017-03-23 11:04:48 -0700526}
527
michaelt79e05882016-11-08 02:50:09 -0800528void AudioSendStream::SetTransportOverhead(int transport_overhead_per_packet) {
elad.alond12a8e12017-03-23 11:04:48 -0700529 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100530 channel_send_->SetTransportOverhead(transport_overhead_per_packet);
michaelt79e05882016-11-08 02:50:09 -0800531}
532
ossuc3d4b482017-05-23 06:07:11 -0700533RtpState AudioSendStream::GetRtpState() const {
534 return rtp_rtcp_module_->GetRtpState();
535}
536
Niels Möllerdced9f62018-11-19 10:27:07 +0100537const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
538 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100539}
540
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100541internal::AudioState* AudioSendStream::audio_state() {
542 internal::AudioState* audio_state =
543 static_cast<internal::AudioState*>(audio_state_.get());
544 RTC_DCHECK(audio_state);
545 return audio_state;
546}
547
548const internal::AudioState* AudioSendStream::audio_state() const {
549 internal::AudioState* audio_state =
550 static_cast<internal::AudioState*>(audio_state_.get());
551 RTC_DCHECK(audio_state);
552 return audio_state;
553}
554
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100555void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
556 size_t num_channels) {
557 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
558 encoder_sample_rate_hz_ = sample_rate_hz;
559 encoder_num_channels_ = num_channels;
560 if (sending_) {
561 // Update AudioState's information about the stream.
562 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
563 }
564}
565
minyue7a973442016-10-20 03:27:12 -0700566// Apply current codec settings to a single voe::Channel used for sending.
ossu20a4b3f2017-04-27 02:08:52 -0700567bool AudioSendStream::SetupSendCodec(AudioSendStream* stream,
568 const Config& new_config) {
569 RTC_DCHECK(new_config.send_codec_spec);
570 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700571
572 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700573 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100574 new_config.encoder_factory->MakeAudioEncoder(
575 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700576
ossu20a4b3f2017-04-27 02:08:52 -0700577 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200578 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
579 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700580 return false;
581 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200582
583 // If other side does not support audio TWCC and WebRTC-Audio-ABWENoTWCC is
584 // not enabled, do not update target audio bitrate if we are in
585 // WebRTC-Audio-SendSideBwe-For-Video experiment
586 const bool do_not_update_target_bitrate =
587 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC") &&
588 webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe-For-Video") &&
589 !FindExtensionIds(new_config.rtp.extensions).transport_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700590 // If a bitrate has been specified for the codec, use it over the
591 // codec's default.
Alex Narestbbbe4e12018-07-13 10:32:58 +0200592 if (!do_not_update_target_bitrate && spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700593 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700594 }
595
ossu20a4b3f2017-04-27 02:08:52 -0700596 // Enable ANA if configured (currently only used by Opus).
597 if (new_config.audio_network_adaptor_config) {
598 if (encoder->EnableAudioNetworkAdaptor(
599 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100600 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
601 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700602 } else {
603 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700604 }
minyue7a973442016-10-20 03:27:12 -0700605 }
606
ossu20a4b3f2017-04-27 02:08:52 -0700607 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
608 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100609 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700610 cng_config.num_channels = encoder->NumChannels();
611 cng_config.payload_type = *spec.cng_payload_type;
612 cng_config.speech_encoder = std::move(encoder);
613 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100614 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700615
616 stream->RegisterCngPayloadType(
617 *spec.cng_payload_type,
618 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700619 }
ossu20a4b3f2017-04-27 02:08:52 -0700620
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100621 stream->StoreEncoderProperties(encoder->SampleRateHz(),
622 encoder->NumChannels());
Niels Möllerdced9f62018-11-19 10:27:07 +0100623 stream->channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
624 std::move(encoder));
minyue7a973442016-10-20 03:27:12 -0700625 return true;
626}
627
ossu20a4b3f2017-04-27 02:08:52 -0700628bool AudioSendStream::ReconfigureSendCodec(AudioSendStream* stream,
629 const Config& new_config) {
630 const auto& old_config = stream->config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200631
632 if (!new_config.send_codec_spec) {
633 // We cannot de-configure a send codec. So we will do nothing.
634 // By design, the send codec should have not been configured.
635 RTC_DCHECK(!old_config.send_codec_spec);
636 return true;
637 }
638
639 if (new_config.send_codec_spec == old_config.send_codec_spec &&
640 new_config.audio_network_adaptor_config ==
641 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700642 return true;
643 }
644
645 // If we have no encoder, or the format or payload type's changed, create a
646 // new encoder.
647 if (!old_config.send_codec_spec ||
648 new_config.send_codec_spec->format !=
649 old_config.send_codec_spec->format ||
650 new_config.send_codec_spec->payload_type !=
651 old_config.send_codec_spec->payload_type) {
652 return SetupSendCodec(stream, new_config);
653 }
654
Alex Narestbbbe4e12018-07-13 10:32:58 +0200655 // If other side does not support audio TWCC and WebRTC-Audio-ABWENoTWCC is
656 // not enabled, do not update target audio bitrate if we are in
657 // WebRTC-Audio-SendSideBwe-For-Video experiment
658 const bool do_not_update_target_bitrate =
659 !webrtc::field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC") &&
660 webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe-For-Video") &&
661 !FindExtensionIds(new_config.rtp.extensions).transport_sequence_number;
662
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200663 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700664 new_config.send_codec_spec->target_bitrate_bps;
665 // If a bitrate has been specified for the codec, use it over the
666 // codec's default.
Alex Narestbbbe4e12018-07-13 10:32:58 +0200667 if (!do_not_update_target_bitrate && new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700668 new_target_bitrate_bps !=
669 old_config.send_codec_spec->target_bitrate_bps) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100670 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700671 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
672 });
673 }
674
675 ReconfigureANA(stream, new_config);
676 ReconfigureCNG(stream, new_config);
677
678 return true;
679}
680
681void AudioSendStream::ReconfigureANA(AudioSendStream* stream,
682 const Config& new_config) {
683 if (new_config.audio_network_adaptor_config ==
684 stream->config_.audio_network_adaptor_config) {
685 return;
686 }
687 if (new_config.audio_network_adaptor_config) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100688 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700689 if (encoder->EnableAudioNetworkAdaptor(
690 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100691 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
692 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700693 } else {
694 RTC_NOTREACHED();
695 }
696 });
697 } else {
Niels Möllerdced9f62018-11-19 10:27:07 +0100698 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700699 encoder->DisableAudioNetworkAdaptor();
700 });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100701 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
702 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700703 }
704}
705
706void AudioSendStream::ReconfigureCNG(AudioSendStream* stream,
707 const Config& new_config) {
708 if (new_config.send_codec_spec->cng_payload_type ==
709 stream->config_.send_codec_spec->cng_payload_type) {
710 return;
711 }
712
ossu3b9ff382017-04-27 08:03:42 -0700713 // Register the CNG payload type if it's been added, don't do anything if CNG
714 // is removed. Payload types must not be redefined.
715 if (new_config.send_codec_spec->cng_payload_type) {
716 stream->RegisterCngPayloadType(
717 *new_config.send_codec_spec->cng_payload_type,
718 new_config.send_codec_spec->format.clockrate_hz);
719 }
720
ossu20a4b3f2017-04-27 02:08:52 -0700721 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Niels Möllerdced9f62018-11-19 10:27:07 +0100722 stream->channel_send_->ModifyEncoder(
ossu20a4b3f2017-04-27 02:08:52 -0700723 [&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
724 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
725 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
726 if (!sub_encoders.empty()) {
727 // Replace enc with its sub encoder. We need to put the sub
728 // encoder in a temporary first, since otherwise the old value
729 // of enc would be destroyed before the new value got assigned,
730 // which would be bad since the new value is a part of the old
731 // value.
732 auto tmp = std::move(sub_encoders[0]);
733 old_encoder = std::move(tmp);
734 }
735 if (new_config.send_codec_spec->cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100736 AudioEncoderCngConfig config;
ossu20a4b3f2017-04-27 02:08:52 -0700737 config.speech_encoder = std::move(old_encoder);
738 config.num_channels = config.speech_encoder->NumChannels();
739 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
740 config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100741 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
ossu20a4b3f2017-04-27 02:08:52 -0700742 } else {
743 *encoder_ptr = std::move(old_encoder);
744 }
745 });
746}
747
748void AudioSendStream::ReconfigureBitrateObserver(
749 AudioSendStream* stream,
750 const webrtc::AudioSendStream::Config& new_config) {
751 // Since the Config's default is for both of these to be -1, this test will
752 // allow us to configure the bitrate observer if the new config has bitrate
753 // limits set, but would only have us call RemoveBitrateObserver if we were
754 // previously configured with bitrate limits.
Alex Narestcedd3512017-12-07 20:54:55 +0100755 int new_transport_seq_num_id =
756 FindExtensionIds(new_config.rtp.extensions).transport_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700757 if (stream->config_.min_bitrate_bps == new_config.min_bitrate_bps &&
Alex Narestcedd3512017-12-07 20:54:55 +0100758 stream->config_.max_bitrate_bps == new_config.max_bitrate_bps &&
Seth Hampson24722b32017-12-22 09:36:42 -0800759 stream->config_.bitrate_priority == new_config.bitrate_priority &&
Alex Narestcedd3512017-12-07 20:54:55 +0100760 (FindExtensionIds(stream->config_.rtp.extensions)
761 .transport_sequence_number == new_transport_seq_num_id ||
762 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
ossu20a4b3f2017-04-27 02:08:52 -0700763 return;
764 }
765
Sebastian Jansson763e9472018-03-21 12:46:56 +0100766 bool has_transport_sequence_number = new_transport_seq_num_id != 0;
Alex Narestcedd3512017-12-07 20:54:55 +0100767 if (new_config.min_bitrate_bps != -1 && new_config.max_bitrate_bps != -1 &&
Tim Haloun648d28a2018-10-18 16:52:22 -0700768 !new_config.has_dscp &&
Sebastian Jansson763e9472018-03-21 12:46:56 +0100769 (has_transport_sequence_number ||
Alex Narestcedd3512017-12-07 20:54:55 +0100770 !webrtc::field_trial::IsEnabled("WebRTC-Audio-SendSideBwe"))) {
Niels Möller7d76a312018-10-26 12:57:07 +0200771 stream->rtp_transport_->packet_sender()->SetAccountForAudioPackets(true);
Sebastian Jansson763e9472018-03-21 12:46:56 +0100772 stream->ConfigureBitrateObserver(
773 new_config.min_bitrate_bps, new_config.max_bitrate_bps,
774 new_config.bitrate_priority, has_transport_sequence_number);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200775 stream->rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700776 } else {
Niels Möller7d76a312018-10-26 12:57:07 +0200777 stream->rtp_transport_->packet_sender()->SetAccountForAudioPackets(false);
ossu20a4b3f2017-04-27 02:08:52 -0700778 stream->RemoveBitrateObserver();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200779 stream->rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700780 }
781}
782
783void AudioSendStream::ConfigureBitrateObserver(int min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800784 int max_bitrate_bps,
Sebastian Jansson763e9472018-03-21 12:46:56 +0100785 double bitrate_priority,
786 bool has_packet_feedback) {
ossu20a4b3f2017-04-27 02:08:52 -0700787 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
788 RTC_DCHECK_GE(max_bitrate_bps, min_bitrate_bps);
Niels Möllerc572ff32018-11-07 08:43:50 +0100789 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700790 worker_queue_->PostTask([&] {
791 // We may get a callback immediately as the observer is registered, so make
792 // sure the bitrate limits in config_ are up-to-date.
793 config_.min_bitrate_bps = min_bitrate_bps;
794 config_.max_bitrate_bps = max_bitrate_bps;
Seth Hampson24722b32017-12-22 09:36:42 -0800795 config_.bitrate_priority = bitrate_priority;
796 // This either updates the current observer or adds a new observer.
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200797 bitrate_allocator_->AddObserver(
798 this, MediaStreamAllocationConfig{
799 static_cast<uint32_t>(min_bitrate_bps),
800 static_cast<uint32_t>(max_bitrate_bps), 0, true,
801 config_.track_id, bitrate_priority, has_packet_feedback});
ossu20a4b3f2017-04-27 02:08:52 -0700802 thread_sync_event.Set();
803 });
804 thread_sync_event.Wait(rtc::Event::kForever);
805}
806
807void AudioSendStream::RemoveBitrateObserver() {
808 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerc572ff32018-11-07 08:43:50 +0100809 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700810 worker_queue_->PostTask([this, &thread_sync_event] {
811 bitrate_allocator_->RemoveObserver(this);
812 thread_sync_event.Set();
813 });
814 thread_sync_event.Wait(rtc::Event::kForever);
815}
816
ossu3b9ff382017-04-27 08:03:42 -0700817void AudioSendStream::RegisterCngPayloadType(int payload_type,
818 int clockrate_hz) {
ossu3b9ff382017-04-27 08:03:42 -0700819 const CodecInst codec = {payload_type, "CN", clockrate_hz, 0, 1, 0};
ossuc3d4b482017-05-23 06:07:11 -0700820 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
821 rtp_rtcp_module_->DeRegisterSendPayload(codec.pltype);
822 if (rtp_rtcp_module_->RegisterSendPayload(codec) != 0) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100823 RTC_DLOG(LS_ERROR) << "RegisterCngPayloadType() failed to register CN to "
824 "RTP/RTCP module";
ossu3b9ff382017-04-27 08:03:42 -0700825 }
826 }
827}
solenbergc7a8b082015-10-16 14:35:07 -0700828} // namespace internal
829} // namespace webrtc