blob: 8ced40eacd87f87221f11e93fa30c2a97c752ba5 [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"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "api/crypto/frame_encryptor_interface.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"
Oskar Sundbom56ef3052018-10-30 16:11:02 +010029#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
30#include "logging/rtc_event_log/rtc_event_log.h"
31#include "logging/rtc_event_log/rtc_stream_config.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "modules/audio_processing/include/audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/checks.h"
35#include "rtc_base/event.h"
36#include "rtc_base/function_view.h"
37#include "rtc_base/logging.h"
Jonas Olssonabbe8412018-04-03 13:40:05 +020038#include "rtc_base/strings/audio_format_to_string.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/task_queue.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/time_utils.h"
Alex Narestcedd3512017-12-07 20:54:55 +010041#include "system_wrappers/include/field_trial.h"
solenbergc7a8b082015-10-16 14:35:07 -070042
43namespace webrtc {
solenbergc7a8b082015-10-16 14:35:07 -070044namespace internal {
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010045namespace {
eladalonedd6eea2017-05-25 00:15:35 -070046// TODO(eladalon): Subsequent CL will make these values experiment-dependent.
elad.alond12a8e12017-03-23 11:04:48 -070047constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
48constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
49constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
50
Niels Möllerdced9f62018-11-19 10:27:07 +010051void CallEncoder(const std::unique_ptr<voe::ChannelSendInterface>& channel_send,
ossu20a4b3f2017-04-27 02:08:52 -070052 rtc::FunctionView<void(AudioEncoder*)> lambda) {
Niels Möllerdced9f62018-11-19 10:27:07 +010053 channel_send->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
ossu20a4b3f2017-04-27 02:08:52 -070054 RTC_DCHECK(encoder_ptr);
55 lambda(encoder_ptr->get());
56 });
57}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010058
Oskar Sundbom56ef3052018-10-30 16:11:02 +010059void UpdateEventLogStreamConfig(RtcEventLog* event_log,
60 const AudioSendStream::Config& config,
61 const AudioSendStream::Config* old_config) {
62 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
63 // Only update if any of the things we log have changed.
64 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
65 const absl::optional<SendCodecSpec>& b) {
66 if (a.has_value() && b.has_value()) {
67 return a->format.name == b->format.name &&
68 a->payload_type == b->payload_type;
69 }
70 return !a.has_value() && !b.has_value();
71 };
72
73 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
74 config.rtp.extensions == old_config->rtp.extensions &&
75 payload_types_equal(config.send_codec_spec,
76 old_config->send_codec_spec)) {
77 return;
78 }
79
80 auto rtclog_config = absl::make_unique<rtclog::StreamConfig>();
81 rtclog_config->local_ssrc = config.rtp.ssrc;
82 rtclog_config->rtp_extensions = config.rtp.extensions;
83 if (config.send_codec_spec) {
84 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
85 config.send_codec_spec->payload_type, 0);
86 }
87 event_log->Log(absl::make_unique<RtcEventAudioSendStreamConfig>(
88 std::move(rtclog_config)));
89}
90
ossu20a4b3f2017-04-27 02:08:52 -070091} // namespace
92
solenberg566ef242015-11-06 15:34:49 -080093AudioSendStream::AudioSendStream(
94 const webrtc::AudioSendStream::Config& config,
Stefan Holmerb86d4e42015-12-07 10:26:18 +010095 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
perkj26091b12016-09-01 01:17:40 -070096 rtc::TaskQueue* worker_queue,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +010097 ProcessThread* module_process_thread,
Niels Möller7d76a312018-10-26 12:57:07 +020098 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +020099 BitrateAllocatorInterface* bitrate_allocator,
michaelt9332b7d2016-11-30 07:51:13 -0800100 RtcEventLog* event_log,
ossuc3d4b482017-05-23 06:07:11 -0700101 RtcpRttStats* rtcp_rtt_stats,
Sam Zackrissonff058162018-11-20 17:15:13 +0100102 const absl::optional<RtpState>& suspended_rtp_state)
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100103 : AudioSendStream(config,
104 audio_state,
105 worker_queue,
Niels Möller7d76a312018-10-26 12:57:07 +0200106 rtp_transport,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100107 bitrate_allocator,
108 event_log,
109 rtcp_rtt_stats,
110 suspended_rtp_state,
Niels Möllerdced9f62018-11-19 10:27:07 +0100111 voe::CreateChannelSend(worker_queue,
112 module_process_thread,
113 config.media_transport,
Anton Sukhanov626015d2019-02-04 15:16:06 -0800114 /*overhead_observer=*/this,
Niels Möllere9771992018-11-26 10:55:07 +0100115 config.send_transport,
Niels Möllerdced9f62018-11-19 10:27:07 +0100116 rtcp_rtt_stats,
117 event_log,
118 config.frame_encryptor,
119 config.crypto_options,
120 config.rtp.extmap_allow_mixed,
121 config.rtcp_report_interval_ms)) {}
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100122
123AudioSendStream::AudioSendStream(
124 const webrtc::AudioSendStream::Config& config,
125 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
126 rtc::TaskQueue* worker_queue,
Niels Möller7d76a312018-10-26 12:57:07 +0200127 RtpTransportControllerSendInterface* rtp_transport,
Niels Möller67b011d2018-10-22 13:00:40 +0200128 BitrateAllocatorInterface* bitrate_allocator,
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100129 RtcEventLog* event_log,
130 RtcpRttStats* rtcp_rtt_stats,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200131 const absl::optional<RtpState>& suspended_rtp_state,
Niels Möllerdced9f62018-11-19 10:27:07 +0100132 std::unique_ptr<voe::ChannelSendInterface> channel_send)
perkj26091b12016-09-01 01:17:40 -0700133 : worker_queue_(worker_queue),
Niels Möller7d76a312018-10-26 12:57:07 +0200134 config_(Config(/*send_transport=*/nullptr,
135 /*media_transport=*/nullptr)),
mflodman86cc6ff2016-07-26 04:44:06 -0700136 audio_state_(audio_state),
Niels Möllerdced9f62018-11-19 10:27:07 +0100137 channel_send_(std::move(channel_send)),
ossu20a4b3f2017-04-27 02:08:52 -0700138 event_log_(event_log),
michaeltf4caaab2017-01-16 23:55:07 -0800139 bitrate_allocator_(bitrate_allocator),
Niels Möller7d76a312018-10-26 12:57:07 +0200140 rtp_transport_(rtp_transport),
elad.alond12a8e12017-03-23 11:04:48 -0700141 packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
142 kPacketLossRateMinNumAckedPackets,
ossuc3d4b482017-05-23 06:07:11 -0700143 kRecoverablePacketLossRateMinNumAckedPairs),
144 rtp_rtcp_module_(nullptr),
Sam Zackrissonff058162018-11-20 17:15:13 +0100145 suspended_rtp_state_(suspended_rtp_state) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100146 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100147 RTC_DCHECK(worker_queue_);
148 RTC_DCHECK(audio_state_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100149 RTC_DCHECK(channel_send_);
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100150 RTC_DCHECK(bitrate_allocator_);
Niels Möller7d76a312018-10-26 12:57:07 +0200151 // TODO(nisse): Eventually, we should have only media_transport. But for the
152 // time being, we can have either. When media transport is injected, there
153 // should be no rtp_transport, and below check should be strengthened to XOR
154 // (either rtp_transport or media_transport but not both).
155 RTC_DCHECK(rtp_transport || config.media_transport);
Anton Sukhanov626015d2019-02-04 15:16:06 -0800156 if (config.media_transport) {
157 // TODO(sukhanov): Currently media transport audio overhead is considered
158 // constant, we will not get overhead_observer calls when using
159 // media_transport. In the future when we introduce RTP media transport we
160 // should make audio overhead interface consistent and work for both RTP and
161 // non-RTP implementations.
162 audio_overhead_per_packet_bytes_ =
163 config.media_transport->GetAudioPacketOverhead();
164 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100165 rtp_rtcp_module_ = channel_send_->GetRtpRtcp();
ossuc3d4b482017-05-23 06:07:11 -0700166 RTC_DCHECK(rtp_rtcp_module_);
mflodman3d7db262016-04-29 00:57:13 -0700167
ossu20a4b3f2017-04-27 02:08:52 -0700168 ConfigureStream(this, config, true);
elad.alond12a8e12017-03-23 11:04:48 -0700169
170 pacer_thread_checker_.DetachFromThread();
Niels Möller7d76a312018-10-26 12:57:07 +0200171 if (rtp_transport_) {
172 // Signal congestion controller this object is ready for OnPacket*
173 // callbacks.
174 rtp_transport_->RegisterPacketFeedbackObserver(this);
175 }
solenbergc7a8b082015-10-16 14:35:07 -0700176}
177
178AudioSendStream::~AudioSendStream() {
elad.alond12a8e12017-03-23 11:04:48 -0700179 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Jonas Olsson24ea8222018-01-25 10:14:29 +0100180 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100181 RTC_DCHECK(!sending_);
Niels Möller7d76a312018-10-26 12:57:07 +0200182 if (rtp_transport_) {
183 rtp_transport_->DeRegisterPacketFeedbackObserver(this);
Niels Möllerdced9f62018-11-19 10:27:07 +0100184 channel_send_->ResetSenderCongestionControlObjects();
Niels Möller7d76a312018-10-26 12:57:07 +0200185 }
solenbergc7a8b082015-10-16 14:35:07 -0700186}
187
eladalonabbc4302017-07-26 02:09:44 -0700188const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
189 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
190 return config_;
191}
192
ossu20a4b3f2017-04-27 02:08:52 -0700193void AudioSendStream::Reconfigure(
194 const webrtc::AudioSendStream::Config& new_config) {
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100195 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
ossu20a4b3f2017-04-27 02:08:52 -0700196 ConfigureStream(this, new_config, false);
197}
198
Alex Narestcedd3512017-12-07 20:54:55 +0100199AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
200 const std::vector<RtpExtension>& extensions) {
201 ExtensionIds ids;
202 for (const auto& extension : extensions) {
203 if (extension.uri == RtpExtension::kAudioLevelUri) {
204 ids.audio_level = extension.id;
205 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
206 ids.transport_sequence_number = extension.id;
Steve Antonbb50ce52018-03-26 10:24:32 -0700207 } else if (extension.uri == RtpExtension::kMidUri) {
208 ids.mid = extension.id;
Amit Hilbuch77938e62018-12-21 09:23:38 -0800209 } else if (extension.uri == RtpExtension::kRidUri) {
210 ids.rid = extension.id;
211 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
212 ids.repaired_rid = extension.id;
Alex Narestcedd3512017-12-07 20:54:55 +0100213 }
214 }
215 return ids;
216}
217
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100218int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
219 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
220}
221
ossu20a4b3f2017-04-27 02:08:52 -0700222void AudioSendStream::ConfigureStream(
223 webrtc::internal::AudioSendStream* stream,
224 const webrtc::AudioSendStream::Config& new_config,
225 bool first_time) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100226 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
227 << new_config.ToString();
Oskar Sundbom56ef3052018-10-30 16:11:02 +0100228 UpdateEventLogStreamConfig(stream->event_log_, new_config,
229 first_time ? nullptr : &stream->config_);
230
Niels Möllerdced9f62018-11-19 10:27:07 +0100231 const auto& channel_send = stream->channel_send_;
ossu20a4b3f2017-04-27 02:08:52 -0700232 const auto& old_config = stream->config_;
233
Niels Möllere9771992018-11-26 10:55:07 +0100234 // Configuration parameters which cannot be changed.
235 RTC_DCHECK(first_time ||
236 old_config.send_transport == new_config.send_transport);
237
ossu20a4b3f2017-04-27 02:08:52 -0700238 if (first_time || old_config.rtp.ssrc != new_config.rtp.ssrc) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100239 channel_send->SetLocalSSRC(new_config.rtp.ssrc);
ossuc3d4b482017-05-23 06:07:11 -0700240 if (stream->suspended_rtp_state_) {
241 stream->rtp_rtcp_module_->SetRtpState(*stream->suspended_rtp_state_);
242 }
ossu20a4b3f2017-04-27 02:08:52 -0700243 }
244 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100245 channel_send->SetRTCP_CNAME(new_config.rtp.c_name);
ossu20a4b3f2017-04-27 02:08:52 -0700246 }
ossu20a4b3f2017-04-27 02:08:52 -0700247
Benjamin Wright84583f62018-10-04 14:22:34 -0700248 // Enable the frame encryptor if a new frame encryptor has been provided.
249 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100250 channel_send->SetFrameEncryptor(new_config.frame_encryptor);
Benjamin Wright84583f62018-10-04 14:22:34 -0700251 }
252
Johannes Kron9190b822018-10-29 11:22:05 +0100253 if (first_time ||
254 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100255 channel_send->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
Johannes Kron9190b822018-10-29 11:22:05 +0100256 }
257
Alex Narestcedd3512017-12-07 20:54:55 +0100258 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
259 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
ossu20a4b3f2017-04-27 02:08:52 -0700260 // Audio level indication
261 if (first_time || new_ids.audio_level != old_ids.audio_level) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100262 channel_send->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
263 new_ids.audio_level);
ossu20a4b3f2017-04-27 02:08:52 -0700264 }
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100265 bool transport_seq_num_id_changed =
266 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100267 if (first_time || (transport_seq_num_id_changed &&
268 !stream->allocation_settings_.ForceNoAudioFeedback())) {
ossu1129df22017-06-30 01:38:56 -0700269 if (!first_time) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100270 channel_send->ResetSenderCongestionControlObjects();
ossu20a4b3f2017-04-27 02:08:52 -0700271 }
272
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100273 RtcpBandwidthObserver* bandwidth_observer = nullptr;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100274
275 if (stream->allocation_settings_.IncludeAudioInFeedback(
276 new_ids.transport_sequence_number != 0)) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100277 channel_send->EnableSendTransportSequenceNumber(
ossu20a4b3f2017-04-27 02:08:52 -0700278 new_ids.transport_sequence_number);
Sebastian Jansson8d9c5402017-11-15 17:22:16 +0100279 // Probing in application limited region is only used in combination with
280 // send side congestion control, wich depends on feedback packets which
281 // requires transport sequence numbers to be enabled.
Niels Möller7d76a312018-10-26 12:57:07 +0200282 if (stream->rtp_transport_) {
283 stream->rtp_transport_->EnablePeriodicAlrProbing(true);
284 bandwidth_observer = stream->rtp_transport_->GetBandwidthObserver();
285 }
ossu20a4b3f2017-04-27 02:08:52 -0700286 }
Niels Möller7d76a312018-10-26 12:57:07 +0200287 if (stream->rtp_transport_) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100288 channel_send->RegisterSenderCongestionControlObjects(
Niels Möller7d76a312018-10-26 12:57:07 +0200289 stream->rtp_transport_, bandwidth_observer);
290 }
ossu20a4b3f2017-04-27 02:08:52 -0700291 }
Steve Antonbb50ce52018-03-26 10:24:32 -0700292 // MID RTP header extension.
Steve Anton003930a2018-03-29 12:37:21 -0700293 if ((first_time || new_ids.mid != old_ids.mid ||
294 new_config.rtp.mid != old_config.rtp.mid) &&
295 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100296 channel_send->SetMid(new_config.rtp.mid, new_ids.mid);
Steve Antonbb50ce52018-03-26 10:24:32 -0700297 }
298
Amit Hilbuch77938e62018-12-21 09:23:38 -0800299 // RID RTP header extension
300 if ((first_time || new_ids.rid != old_ids.rid ||
301 new_ids.repaired_rid != old_ids.repaired_rid ||
302 new_config.rtp.rid != old_config.rtp.rid)) {
303 channel_send->SetRid(new_config.rtp.rid, new_ids.rid, new_ids.repaired_rid);
304 }
305
ossu20a4b3f2017-04-27 02:08:52 -0700306 if (!ReconfigureSendCodec(stream, new_config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100307 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
ossu20a4b3f2017-04-27 02:08:52 -0700308 }
309
Oskar Sundbomf85e31b2017-12-20 16:38:09 +0100310 if (stream->sending_) {
311 ReconfigureBitrateObserver(stream, new_config);
312 }
ossu20a4b3f2017-04-27 02:08:52 -0700313 stream->config_ = new_config;
314}
315
solenberg3a941542015-11-16 07:34:50 -0800316void AudioSendStream::Start() {
elad.alond12a8e12017-03-23 11:04:48 -0700317 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100318 if (sending_) {
319 return;
320 }
321
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100322 if (allocation_settings_.IncludeAudioInAllocationOnStart(
323 config_.min_bitrate_bps, config_.max_bitrate_bps, config_.has_dscp,
324 TransportSeqNumId(config_))) {
Niels Möller7d76a312018-10-26 12:57:07 +0200325 rtp_transport_->packet_sender()->SetAccountForAudioPackets(true);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200326 rtp_rtcp_module_->SetAsPartOfAllocation(true);
Seth Hampson24722b32017-12-22 09:36:42 -0800327 ConfigureBitrateObserver(config_.min_bitrate_bps, config_.max_bitrate_bps,
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100328 config_.bitrate_priority);
Sebastian Janssonb6863962018-10-10 10:23:13 +0200329 } else {
330 rtp_rtcp_module_->SetAsPartOfAllocation(false);
mflodman86cc6ff2016-07-26 04:44:06 -0700331 }
Niels Möllerdced9f62018-11-19 10:27:07 +0100332 channel_send_->StartSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100333 sending_ = true;
334 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
335 encoder_num_channels_);
solenberg3a941542015-11-16 07:34:50 -0800336}
337
338void AudioSendStream::Stop() {
elad.alond12a8e12017-03-23 11:04:48 -0700339 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100340 if (!sending_) {
341 return;
342 }
343
ossu20a4b3f2017-04-27 02:08:52 -0700344 RemoveBitrateObserver();
Niels Möllerdced9f62018-11-19 10:27:07 +0100345 channel_send_->StopSend();
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100346 sending_ = false;
347 audio_state()->RemoveSendingStream(this);
348}
349
350void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
351 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100352 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
solenberg3a941542015-11-16 07:34:50 -0800353}
354
solenbergffbbcac2016-11-17 05:25:37 -0800355bool AudioSendStream::SendTelephoneEvent(int payload_type,
Yves Gerey665174f2018-06-19 15:03:05 +0200356 int payload_frequency,
357 int event,
solenberg8842c3e2016-03-11 03:06:41 -0800358 int duration_ms) {
elad.alond12a8e12017-03-23 11:04:48 -0700359 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100360 return channel_send_->SetSendTelephoneEventPayloadType(payload_type,
361 payload_frequency) &&
362 channel_send_->SendTelephoneEventOutband(event, duration_ms);
Fredrik Solenbergb5727682015-12-04 15:22:19 +0100363}
364
solenberg94218532016-06-16 10:53:22 -0700365void AudioSendStream::SetMuted(bool muted) {
elad.alond12a8e12017-03-23 11:04:48 -0700366 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100367 channel_send_->SetInputMute(muted);
solenberg94218532016-06-16 10:53:22 -0700368}
369
solenbergc7a8b082015-10-16 14:35:07 -0700370webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
Ivo Creusen56d46092017-11-24 17:29:59 +0100371 return GetStats(true);
372}
373
374webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
375 bool has_remote_tracks) const {
elad.alond12a8e12017-03-23 11:04:48 -0700376 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
solenberg85a04962015-10-27 03:35:21 -0700377 webrtc::AudioSendStream::Stats stats;
378 stats.local_ssrc = config_.rtp.ssrc;
Niels Möllerdced9f62018-11-19 10:27:07 +0100379 stats.target_bitrate_bps = channel_send_->GetBitrate();
solenberg85a04962015-10-27 03:35:21 -0700380
Niels Möllerdced9f62018-11-19 10:27:07 +0100381 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
solenberg85a04962015-10-27 03:35:21 -0700382 stats.bytes_sent = call_stats.bytesSent;
383 stats.packets_sent = call_stats.packetsSent;
solenberg8b85de22015-11-16 09:48:04 -0800384 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
385 // returns 0 to indicate an error value.
386 if (call_stats.rttMs > 0) {
387 stats.rtt_ms = call_stats.rttMs;
388 }
ossu20a4b3f2017-04-27 02:08:52 -0700389 if (config_.send_codec_spec) {
390 const auto& spec = *config_.send_codec_spec;
391 stats.codec_name = spec.format.name;
Oskar Sundbom2707fb22017-11-16 10:57:35 +0100392 stats.codec_payload_type = spec.payload_type;
solenberg85a04962015-10-27 03:35:21 -0700393
394 // Get data from the last remote RTCP report.
Niels Möllerdced9f62018-11-19 10:27:07 +0100395 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
solenberg8b85de22015-11-16 09:48:04 -0800396 // Lookup report for send ssrc only.
397 if (block.source_SSRC == stats.local_ssrc) {
398 stats.packets_lost = block.cumulative_num_packets_lost;
399 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
400 stats.ext_seqnum = block.extended_highest_sequence_number;
ossu20a4b3f2017-04-27 02:08:52 -0700401 // Convert timestamps to milliseconds.
402 if (spec.format.clockrate_hz / 1000 > 0) {
solenberg8b85de22015-11-16 09:48:04 -0800403 stats.jitter_ms =
ossu20a4b3f2017-04-27 02:08:52 -0700404 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
solenberg85a04962015-10-27 03:35:21 -0700405 }
solenberg8b85de22015-11-16 09:48:04 -0800406 break;
solenberg85a04962015-10-27 03:35:21 -0700407 }
408 }
409 }
410
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100411 AudioState::Stats input_stats = audio_state()->GetAudioInputStats();
412 stats.audio_level = input_stats.audio_level;
413 stats.total_input_energy = input_stats.total_energy;
414 stats.total_input_duration = input_stats.total_duration;
solenberg796b8f92017-03-01 17:02:23 -0800415
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100416 stats.typing_noise_detected = audio_state()->typing_noise_detected();
Niels Möllerdced9f62018-11-19 10:27:07 +0100417 stats.ana_statistics = channel_send_->GetANAStatistics();
Ivo Creusen56d46092017-11-24 17:29:59 +0100418 RTC_DCHECK(audio_state_->audio_processing());
419 stats.apm_statistics =
420 audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
solenberg85a04962015-10-27 03:35:21 -0700421
422 return stats;
423}
424
pbos1ba8d392016-05-01 20:18:34 -0700425void AudioSendStream::SignalNetworkState(NetworkState state) {
elad.alond12a8e12017-03-23 11:04:48 -0700426 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
pbos1ba8d392016-05-01 20:18:34 -0700427}
428
429bool AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
430 // TODO(solenberg): Tests call this function on a network thread, libjingle
431 // calls on the worker thread. We should move towards always using a network
432 // thread. Then this check can be enabled.
elad.alond12a8e12017-03-23 11:04:48 -0700433 // RTC_DCHECK(!worker_thread_checker_.CalledOnValidThread());
Niels Möllerdced9f62018-11-19 10:27:07 +0100434 return channel_send_->ReceivedRTCPPacket(packet, length);
pbos1ba8d392016-05-01 20:18:34 -0700435}
436
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200437uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
stefanfca900a2017-04-10 03:53:00 -0700438 // A send stream may be allocated a bitrate of zero if the allocator decides
439 // to disable it. For now we ignore this decision and keep sending on min
440 // bitrate.
Sebastian Jansson13e59032018-11-21 19:13:07 +0100441 if (update.target_bitrate.IsZero()) {
442 update.target_bitrate = DataRate::bps(config_.min_bitrate_bps);
stefanfca900a2017-04-10 03:53:00 -0700443 }
Sebastian Jansson13e59032018-11-21 19:13:07 +0100444 RTC_DCHECK_GE(update.target_bitrate.bps<int>(), config_.min_bitrate_bps);
mflodman86cc6ff2016-07-26 04:44:06 -0700445 // The bitrate allocator might allocate an higher than max configured bitrate
446 // if there is room, to allow for, as example, extra FEC. Ignore that for now.
Sebastian Jansson13e59032018-11-21 19:13:07 +0100447 const DataRate max_bitrate = DataRate::bps(config_.max_bitrate_bps);
448 if (update.target_bitrate > max_bitrate)
449 update.target_bitrate = max_bitrate;
mflodman86cc6ff2016-07-26 04:44:06 -0700450
Sebastian Jansson254d8692018-11-21 19:19:00 +0100451 channel_send_->OnBitrateAllocation(update);
mflodman86cc6ff2016-07-26 04:44:06 -0700452
453 // The amount of audio protection is not exposed by the encoder, hence
454 // always returning 0.
455 return 0;
456}
457
elad.alond12a8e12017-03-23 11:04:48 -0700458void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
459 RTC_DCHECK(pacer_thread_checker_.CalledOnValidThread());
460 // Only packets that belong to this stream are of interest.
461 if (ssrc == config_.rtp.ssrc) {
462 rtc::CritScope lock(&packet_loss_tracker_cs_);
eladalonedd6eea2017-05-25 00:15:35 -0700463 // TODO(eladalon): This function call could potentially reset the window,
elad.alond12a8e12017-03-23 11:04:48 -0700464 // setting both PLR and RPLR to unknown. Consider (during upcoming
465 // refactoring) passing an indication of such an event.
466 packet_loss_tracker_.OnPacketAdded(seq_num, rtc::TimeMillis());
467 }
468}
469
470void AudioSendStream::OnPacketFeedbackVector(
471 const std::vector<PacketFeedback>& packet_feedback_vector) {
eladalon3651fdd2017-08-24 07:26:25 -0700472 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200473 absl::optional<float> plr;
474 absl::optional<float> rplr;
elad.alond12a8e12017-03-23 11:04:48 -0700475 {
476 rtc::CritScope lock(&packet_loss_tracker_cs_);
477 packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
478 plr = packet_loss_tracker_.GetPacketLossRate();
elad.alondadb4dc2017-03-23 15:29:50 -0700479 rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
elad.alond12a8e12017-03-23 11:04:48 -0700480 }
eladalonedd6eea2017-05-25 00:15:35 -0700481 // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
elad.alond12a8e12017-03-23 11:04:48 -0700482 // the previously sent value is no longer relevant. This will be taken care
483 // of with some refactoring which is now being done.
484 if (plr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100485 channel_send_->OnTwccBasedUplinkPacketLossRate(*plr);
elad.alond12a8e12017-03-23 11:04:48 -0700486 }
elad.alondadb4dc2017-03-23 15:29:50 -0700487 if (rplr) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100488 channel_send_->OnRecoverableUplinkPacketLossRate(*rplr);
elad.alondadb4dc2017-03-23 15:29:50 -0700489 }
elad.alond12a8e12017-03-23 11:04:48 -0700490}
491
Anton Sukhanov626015d2019-02-04 15:16:06 -0800492void AudioSendStream::SetTransportOverhead(
493 int transport_overhead_per_packet_bytes) {
elad.alond12a8e12017-03-23 11:04:48 -0700494 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Anton Sukhanov626015d2019-02-04 15:16:06 -0800495 rtc::CritScope cs(&overhead_per_packet_lock_);
496 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
497 UpdateOverheadForEncoder();
498}
499
500void AudioSendStream::OnOverheadChanged(
501 size_t overhead_bytes_per_packet_bytes) {
502 rtc::CritScope cs(&overhead_per_packet_lock_);
503 audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
504 UpdateOverheadForEncoder();
505}
506
507void AudioSendStream::UpdateOverheadForEncoder() {
508 const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
509 CallEncoder(channel_send_, [&](AudioEncoder* encoder) {
510 if (encoder) {
511 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
512 }
513 });
514}
515
516size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
517 rtc::CritScope cs(&overhead_per_packet_lock_);
518 return GetPerPacketOverheadBytes();
519}
520
521size_t AudioSendStream::GetPerPacketOverheadBytes() const {
522 return transport_overhead_per_packet_bytes_ +
523 audio_overhead_per_packet_bytes_;
michaelt79e05882016-11-08 02:50:09 -0800524}
525
ossuc3d4b482017-05-23 06:07:11 -0700526RtpState AudioSendStream::GetRtpState() const {
527 return rtp_rtcp_module_->GetRtpState();
528}
529
Niels Möllerdced9f62018-11-19 10:27:07 +0100530const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
531 return channel_send_.get();
Fredrik Solenberg8f5787a2018-01-11 13:52:30 +0100532}
533
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100534internal::AudioState* AudioSendStream::audio_state() {
535 internal::AudioState* audio_state =
536 static_cast<internal::AudioState*>(audio_state_.get());
537 RTC_DCHECK(audio_state);
538 return audio_state;
539}
540
541const internal::AudioState* AudioSendStream::audio_state() const {
542 internal::AudioState* audio_state =
543 static_cast<internal::AudioState*>(audio_state_.get());
544 RTC_DCHECK(audio_state);
545 return audio_state;
546}
547
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100548void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
549 size_t num_channels) {
550 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
551 encoder_sample_rate_hz_ = sample_rate_hz;
552 encoder_num_channels_ = num_channels;
553 if (sending_) {
554 // Update AudioState's information about the stream.
555 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
556 }
557}
558
minyue7a973442016-10-20 03:27:12 -0700559// Apply current codec settings to a single voe::Channel used for sending.
ossu20a4b3f2017-04-27 02:08:52 -0700560bool AudioSendStream::SetupSendCodec(AudioSendStream* stream,
561 const Config& new_config) {
562 RTC_DCHECK(new_config.send_codec_spec);
563 const auto& spec = *new_config.send_codec_spec;
minyue48368ad2017-05-10 04:06:11 -0700564
565 RTC_DCHECK(new_config.encoder_factory);
ossu20a4b3f2017-04-27 02:08:52 -0700566 std::unique_ptr<AudioEncoder> encoder =
Karl Wiberg77490b92018-03-21 15:18:42 +0100567 new_config.encoder_factory->MakeAudioEncoder(
568 spec.payload_type, spec.format, new_config.codec_pair_id);
minyue7a973442016-10-20 03:27:12 -0700569
ossu20a4b3f2017-04-27 02:08:52 -0700570 if (!encoder) {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200571 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
572 << rtc::ToString(spec.format);
ossu20a4b3f2017-04-27 02:08:52 -0700573 return false;
574 }
Alex Narestbbbe4e12018-07-13 10:32:58 +0200575
ossu20a4b3f2017-04-27 02:08:52 -0700576 // If a bitrate has been specified for the codec, use it over the
577 // codec's default.
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100578 if (stream->allocation_settings_.UpdateAudioTargetBitrate(
579 TransportSeqNumId(new_config)) &&
580 spec.target_bitrate_bps) {
ossu20a4b3f2017-04-27 02:08:52 -0700581 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
minyue7a973442016-10-20 03:27:12 -0700582 }
583
ossu20a4b3f2017-04-27 02:08:52 -0700584 // Enable ANA if configured (currently only used by Opus).
585 if (new_config.audio_network_adaptor_config) {
586 if (encoder->EnableAudioNetworkAdaptor(
587 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100588 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
589 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700590 } else {
591 RTC_NOTREACHED();
minyue6b825df2016-10-31 04:08:32 -0700592 }
minyue7a973442016-10-20 03:27:12 -0700593 }
594
ossu20a4b3f2017-04-27 02:08:52 -0700595 // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
596 if (spec.cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100597 AudioEncoderCngConfig cng_config;
ossu20a4b3f2017-04-27 02:08:52 -0700598 cng_config.num_channels = encoder->NumChannels();
599 cng_config.payload_type = *spec.cng_payload_type;
600 cng_config.speech_encoder = std::move(encoder);
601 cng_config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100602 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
ossu3b9ff382017-04-27 08:03:42 -0700603
604 stream->RegisterCngPayloadType(
605 *spec.cng_payload_type,
606 new_config.send_codec_spec->format.clockrate_hz);
minyue7a973442016-10-20 03:27:12 -0700607 }
ossu20a4b3f2017-04-27 02:08:52 -0700608
Anton Sukhanov626015d2019-02-04 15:16:06 -0800609 // Set currently known overhead (used in ANA, opus only).
610 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
611 {
612 rtc::CritScope cs(&stream->overhead_per_packet_lock_);
613 encoder->OnReceivedOverhead(stream->GetPerPacketOverheadBytes());
614 }
615
Fredrik Solenberg2a877972017-12-15 16:42:15 +0100616 stream->StoreEncoderProperties(encoder->SampleRateHz(),
617 encoder->NumChannels());
Niels Möllerdced9f62018-11-19 10:27:07 +0100618 stream->channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
619 std::move(encoder));
Anton Sukhanov626015d2019-02-04 15:16:06 -0800620
minyue7a973442016-10-20 03:27:12 -0700621 return true;
622}
623
ossu20a4b3f2017-04-27 02:08:52 -0700624bool AudioSendStream::ReconfigureSendCodec(AudioSendStream* stream,
625 const Config& new_config) {
626 const auto& old_config = stream->config_;
minyue-webrtc8de18262017-07-26 14:18:40 +0200627
628 if (!new_config.send_codec_spec) {
629 // We cannot de-configure a send codec. So we will do nothing.
630 // By design, the send codec should have not been configured.
631 RTC_DCHECK(!old_config.send_codec_spec);
632 return true;
633 }
634
635 if (new_config.send_codec_spec == old_config.send_codec_spec &&
636 new_config.audio_network_adaptor_config ==
637 old_config.audio_network_adaptor_config) {
ossu20a4b3f2017-04-27 02:08:52 -0700638 return true;
639 }
640
641 // If we have no encoder, or the format or payload type's changed, create a
642 // new encoder.
643 if (!old_config.send_codec_spec ||
644 new_config.send_codec_spec->format !=
645 old_config.send_codec_spec->format ||
646 new_config.send_codec_spec->payload_type !=
647 old_config.send_codec_spec->payload_type) {
648 return SetupSendCodec(stream, new_config);
649 }
650
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200651 const absl::optional<int>& new_target_bitrate_bps =
ossu20a4b3f2017-04-27 02:08:52 -0700652 new_config.send_codec_spec->target_bitrate_bps;
653 // If a bitrate has been specified for the codec, use it over the
654 // codec's default.
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100655 if (stream->allocation_settings_.UpdateAudioTargetBitrate(
656 TransportSeqNumId(new_config)) &&
657 new_target_bitrate_bps &&
ossu20a4b3f2017-04-27 02:08:52 -0700658 new_target_bitrate_bps !=
659 old_config.send_codec_spec->target_bitrate_bps) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100660 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700661 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
662 });
663 }
664
665 ReconfigureANA(stream, new_config);
666 ReconfigureCNG(stream, new_config);
667
Anton Sukhanov626015d2019-02-04 15:16:06 -0800668 // Set currently known overhead (used in ANA, opus only).
669 {
670 rtc::CritScope cs(&stream->overhead_per_packet_lock_);
671 stream->UpdateOverheadForEncoder();
672 }
673
ossu20a4b3f2017-04-27 02:08:52 -0700674 return true;
675}
676
677void AudioSendStream::ReconfigureANA(AudioSendStream* stream,
678 const Config& new_config) {
679 if (new_config.audio_network_adaptor_config ==
680 stream->config_.audio_network_adaptor_config) {
681 return;
682 }
683 if (new_config.audio_network_adaptor_config) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100684 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700685 if (encoder->EnableAudioNetworkAdaptor(
686 *new_config.audio_network_adaptor_config, stream->event_log_)) {
Jonas Olsson24ea8222018-01-25 10:14:29 +0100687 RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
688 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700689 } else {
690 RTC_NOTREACHED();
691 }
692 });
693 } else {
Niels Möllerdced9f62018-11-19 10:27:07 +0100694 CallEncoder(stream->channel_send_, [&](AudioEncoder* encoder) {
ossu20a4b3f2017-04-27 02:08:52 -0700695 encoder->DisableAudioNetworkAdaptor();
696 });
Jonas Olsson24ea8222018-01-25 10:14:29 +0100697 RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
698 << new_config.rtp.ssrc;
ossu20a4b3f2017-04-27 02:08:52 -0700699 }
700}
701
702void AudioSendStream::ReconfigureCNG(AudioSendStream* stream,
703 const Config& new_config) {
704 if (new_config.send_codec_spec->cng_payload_type ==
705 stream->config_.send_codec_spec->cng_payload_type) {
706 return;
707 }
708
ossu3b9ff382017-04-27 08:03:42 -0700709 // Register the CNG payload type if it's been added, don't do anything if CNG
710 // is removed. Payload types must not be redefined.
711 if (new_config.send_codec_spec->cng_payload_type) {
712 stream->RegisterCngPayloadType(
713 *new_config.send_codec_spec->cng_payload_type,
714 new_config.send_codec_spec->format.clockrate_hz);
715 }
716
ossu20a4b3f2017-04-27 02:08:52 -0700717 // Wrap or unwrap the encoder in an AudioEncoderCNG.
Niels Möllerdced9f62018-11-19 10:27:07 +0100718 stream->channel_send_->ModifyEncoder(
ossu20a4b3f2017-04-27 02:08:52 -0700719 [&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
720 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
721 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
722 if (!sub_encoders.empty()) {
723 // Replace enc with its sub encoder. We need to put the sub
724 // encoder in a temporary first, since otherwise the old value
725 // of enc would be destroyed before the new value got assigned,
726 // which would be bad since the new value is a part of the old
727 // value.
728 auto tmp = std::move(sub_encoders[0]);
729 old_encoder = std::move(tmp);
730 }
731 if (new_config.send_codec_spec->cng_payload_type) {
Karl Wiberg23659362018-11-01 11:13:44 +0100732 AudioEncoderCngConfig config;
ossu20a4b3f2017-04-27 02:08:52 -0700733 config.speech_encoder = std::move(old_encoder);
734 config.num_channels = config.speech_encoder->NumChannels();
735 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
736 config.vad_mode = Vad::kVadNormal;
Karl Wiberg23659362018-11-01 11:13:44 +0100737 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
ossu20a4b3f2017-04-27 02:08:52 -0700738 } else {
739 *encoder_ptr = std::move(old_encoder);
740 }
741 });
742}
743
744void AudioSendStream::ReconfigureBitrateObserver(
745 AudioSendStream* stream,
746 const webrtc::AudioSendStream::Config& new_config) {
747 // Since the Config's default is for both of these to be -1, this test will
748 // allow us to configure the bitrate observer if the new config has bitrate
749 // limits set, but would only have us call RemoveBitrateObserver if we were
750 // previously configured with bitrate limits.
751 if (stream->config_.min_bitrate_bps == new_config.min_bitrate_bps &&
Alex Narestcedd3512017-12-07 20:54:55 +0100752 stream->config_.max_bitrate_bps == new_config.max_bitrate_bps &&
Seth Hampson24722b32017-12-22 09:36:42 -0800753 stream->config_.bitrate_priority == new_config.bitrate_priority &&
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100754 (TransportSeqNumId(stream->config_) == TransportSeqNumId(new_config) ||
755 stream->allocation_settings_.IgnoreSeqNumIdChange())) {
ossu20a4b3f2017-04-27 02:08:52 -0700756 return;
757 }
758
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100759 if (stream->allocation_settings_.IncludeAudioInAllocationOnReconfigure(
760 new_config.min_bitrate_bps, new_config.max_bitrate_bps,
761 new_config.has_dscp, TransportSeqNumId(new_config))) {
Niels Möller7d76a312018-10-26 12:57:07 +0200762 stream->rtp_transport_->packet_sender()->SetAccountForAudioPackets(true);
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100763 stream->ConfigureBitrateObserver(new_config.min_bitrate_bps,
764 new_config.max_bitrate_bps,
765 new_config.bitrate_priority);
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100766 stream->rtp_rtcp_module_->SetAsPartOfAllocation(true);
ossu20a4b3f2017-04-27 02:08:52 -0700767 } else {
Niels Möller7d76a312018-10-26 12:57:07 +0200768 stream->rtp_transport_->packet_sender()->SetAccountForAudioPackets(false);
ossu20a4b3f2017-04-27 02:08:52 -0700769 stream->RemoveBitrateObserver();
Sebastian Janssonb6863962018-10-10 10:23:13 +0200770 stream->rtp_rtcp_module_->SetAsPartOfAllocation(false);
ossu20a4b3f2017-04-27 02:08:52 -0700771 }
772}
773
774void AudioSendStream::ConfigureBitrateObserver(int min_bitrate_bps,
Seth Hampson24722b32017-12-22 09:36:42 -0800775 int max_bitrate_bps,
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100776 double bitrate_priority) {
ossu20a4b3f2017-04-27 02:08:52 -0700777 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
778 RTC_DCHECK_GE(max_bitrate_bps, min_bitrate_bps);
Niels Möllerc572ff32018-11-07 08:43:50 +0100779 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700780 worker_queue_->PostTask([&] {
781 // We may get a callback immediately as the observer is registered, so make
782 // sure the bitrate limits in config_ are up-to-date.
783 config_.min_bitrate_bps = min_bitrate_bps;
784 config_.max_bitrate_bps = max_bitrate_bps;
Seth Hampson24722b32017-12-22 09:36:42 -0800785 config_.bitrate_priority = bitrate_priority;
786 // This either updates the current observer or adds a new observer.
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200787 bitrate_allocator_->AddObserver(
Sebastian Jansson464a5572019-02-12 13:32:32 +0100788 this, MediaStreamAllocationConfig{
789 static_cast<uint32_t>(min_bitrate_bps),
790 static_cast<uint32_t>(max_bitrate_bps), 0,
791 allocation_settings_.DefaultPriorityBitrate().bps(), true,
792 config_.track_id, bitrate_priority});
ossu20a4b3f2017-04-27 02:08:52 -0700793 thread_sync_event.Set();
794 });
795 thread_sync_event.Wait(rtc::Event::kForever);
796}
797
798void AudioSendStream::RemoveBitrateObserver() {
799 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möllerc572ff32018-11-07 08:43:50 +0100800 rtc::Event thread_sync_event;
ossu20a4b3f2017-04-27 02:08:52 -0700801 worker_queue_->PostTask([this, &thread_sync_event] {
802 bitrate_allocator_->RemoveObserver(this);
803 thread_sync_event.Set();
804 });
805 thread_sync_event.Wait(rtc::Event::kForever);
806}
807
ossu3b9ff382017-04-27 08:03:42 -0700808void AudioSendStream::RegisterCngPayloadType(int payload_type,
809 int clockrate_hz) {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100810 rtp_rtcp_module_->RegisterAudioSendPayload(payload_type, "CN", clockrate_hz,
811 1, 0);
ossu3b9ff382017-04-27 08:03:42 -0700812}
solenbergc7a8b082015-10-16 14:35:07 -0700813} // namespace internal
814} // namespace webrtc