1 /*
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
11 #include "audio/audio_send_stream.h"
12
13 #include <memory>
14 #include <string>
15 #include <utility>
16 #include <vector>
17
18 #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/frame_encryptor_interface.h"
23 #include "api/function_view.h"
24 #include "api/rtc_event_log/rtc_event_log.h"
25 #include "api/task_queue/task_queue_base.h"
26 #include "audio/audio_state.h"
27 #include "audio/channel_send.h"
28 #include "audio/conversion.h"
29 #include "call/rtp_config.h"
30 #include "call/rtp_transport_controller_send_interface.h"
31 #include "common_audio/vad/include/vad.h"
32 #include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
33 #include "logging/rtc_event_log/rtc_stream_config.h"
34 #include "media/base/media_channel.h"
35 #include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
36 #include "modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
37 #include "modules/audio_processing/include/audio_processing.h"
38 #include "modules/rtp_rtcp/source/rtp_header_extensions.h"
39 #include "rtc_base/checks.h"
40 #include "rtc_base/logging.h"
41 #include "rtc_base/strings/audio_format_to_string.h"
42 #include "rtc_base/trace_event.h"
43
44 namespace webrtc {
45 namespace {
46
UpdateEventLogStreamConfig(RtcEventLog * event_log,const AudioSendStream::Config & config,const AudioSendStream::Config * old_config)47 void UpdateEventLogStreamConfig(RtcEventLog* event_log,
48 const AudioSendStream::Config& config,
49 const AudioSendStream::Config* old_config) {
50 using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
51 // Only update if any of the things we log have changed.
52 auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
53 const absl::optional<SendCodecSpec>& b) {
54 if (a.has_value() && b.has_value()) {
55 return a->format.name == b->format.name &&
56 a->payload_type == b->payload_type;
57 }
58 return !a.has_value() && !b.has_value();
59 };
60
61 if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
62 config.rtp.extensions == old_config->rtp.extensions &&
63 payload_types_equal(config.send_codec_spec,
64 old_config->send_codec_spec)) {
65 return;
66 }
67
68 auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
69 rtclog_config->local_ssrc = config.rtp.ssrc;
70 rtclog_config->rtp_extensions = config.rtp.extensions;
71 if (config.send_codec_spec) {
72 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
73 config.send_codec_spec->payload_type, 0);
74 }
75 event_log->Log(std::make_unique<RtcEventAudioSendStreamConfig>(
76 std::move(rtclog_config)));
77 }
78
79 } // namespace
80
81 constexpr char AudioAllocationConfig::kKey[];
82
Parser()83 std::unique_ptr<StructParametersParser> AudioAllocationConfig::Parser() {
84 return StructParametersParser::Create( //
85 "min", &min_bitrate, //
86 "max", &max_bitrate, //
87 "prio_rate", &priority_bitrate, //
88 "prio_rate_raw", &priority_bitrate_raw, //
89 "rate_prio", &bitrate_priority);
90 }
91
AudioAllocationConfig(const FieldTrialsView & field_trials)92 AudioAllocationConfig::AudioAllocationConfig(
93 const FieldTrialsView& field_trials) {
94 Parser()->Parse(field_trials.Lookup(kKey));
95 if (priority_bitrate_raw && !priority_bitrate.IsZero()) {
96 RTC_LOG(LS_WARNING) << "'priority_bitrate' and '_raw' are mutually "
97 "exclusive but both were configured.";
98 }
99 }
100
101 namespace internal {
AudioSendStream(Clock * clock,const webrtc::AudioSendStream::Config & config,const rtc::scoped_refptr<webrtc::AudioState> & audio_state,TaskQueueFactory * task_queue_factory,RtpTransportControllerSendInterface * rtp_transport,BitrateAllocatorInterface * bitrate_allocator,RtcEventLog * event_log,RtcpRttStats * rtcp_rtt_stats,const absl::optional<RtpState> & suspended_rtp_state,const FieldTrialsView & field_trials)102 AudioSendStream::AudioSendStream(
103 Clock* clock,
104 const webrtc::AudioSendStream::Config& config,
105 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
106 TaskQueueFactory* task_queue_factory,
107 RtpTransportControllerSendInterface* rtp_transport,
108 BitrateAllocatorInterface* bitrate_allocator,
109 RtcEventLog* event_log,
110 RtcpRttStats* rtcp_rtt_stats,
111 const absl::optional<RtpState>& suspended_rtp_state,
112 const FieldTrialsView& field_trials)
113 : AudioSendStream(
114 clock,
115 config,
116 audio_state,
117 task_queue_factory,
118 rtp_transport,
119 bitrate_allocator,
120 event_log,
121 suspended_rtp_state,
122 voe::CreateChannelSend(clock,
123 task_queue_factory,
124 config.send_transport,
125 rtcp_rtt_stats,
126 event_log,
127 config.frame_encryptor.get(),
128 config.crypto_options,
129 config.rtp.extmap_allow_mixed,
130 config.rtcp_report_interval_ms,
131 config.rtp.ssrc,
132 config.frame_transformer,
133 rtp_transport->transport_feedback_observer(),
134 field_trials),
135 field_trials) {}
136
AudioSendStream(Clock * clock,const webrtc::AudioSendStream::Config & config,const rtc::scoped_refptr<webrtc::AudioState> & audio_state,TaskQueueFactory * task_queue_factory,RtpTransportControllerSendInterface * rtp_transport,BitrateAllocatorInterface * bitrate_allocator,RtcEventLog * event_log,const absl::optional<RtpState> & suspended_rtp_state,std::unique_ptr<voe::ChannelSendInterface> channel_send,const FieldTrialsView & field_trials)137 AudioSendStream::AudioSendStream(
138 Clock* clock,
139 const webrtc::AudioSendStream::Config& config,
140 const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
141 TaskQueueFactory* task_queue_factory,
142 RtpTransportControllerSendInterface* rtp_transport,
143 BitrateAllocatorInterface* bitrate_allocator,
144 RtcEventLog* event_log,
145 const absl::optional<RtpState>& suspended_rtp_state,
146 std::unique_ptr<voe::ChannelSendInterface> channel_send,
147 const FieldTrialsView& field_trials)
148 : clock_(clock),
149 field_trials_(field_trials),
150 rtp_transport_queue_(rtp_transport->GetWorkerQueue()),
151 allocate_audio_without_feedback_(
152 field_trials_.IsEnabled("WebRTC-Audio-ABWENoTWCC")),
153 enable_audio_alr_probing_(
154 !field_trials_.IsDisabled("WebRTC-Audio-AlrProbing")),
155 allocation_settings_(field_trials_),
156 config_(Config(/*send_transport=*/nullptr)),
157 audio_state_(audio_state),
158 channel_send_(std::move(channel_send)),
159 event_log_(event_log),
160 use_legacy_overhead_calculation_(
161 field_trials_.IsEnabled("WebRTC-Audio-LegacyOverhead")),
162 bitrate_allocator_(bitrate_allocator),
163 rtp_transport_(rtp_transport),
164 rtp_rtcp_module_(channel_send_->GetRtpRtcp()),
165 suspended_rtp_state_(suspended_rtp_state) {
166 RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
167 RTC_DCHECK(rtp_transport_queue_);
168 RTC_DCHECK(audio_state_);
169 RTC_DCHECK(channel_send_);
170 RTC_DCHECK(bitrate_allocator_);
171 RTC_DCHECK(rtp_transport);
172
173 RTC_DCHECK(rtp_rtcp_module_);
174
175 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
176 ConfigureStream(config, true, nullptr);
177 UpdateCachedTargetAudioBitrateConstraints();
178 }
179
~AudioSendStream()180 AudioSendStream::~AudioSendStream() {
181 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
182 RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
183 RTC_DCHECK(!sending_);
184 channel_send_->ResetSenderCongestionControlObjects();
185
186 // Blocking call to synchronize state with worker queue to ensure that there
187 // are no pending tasks left that keeps references to audio.
188 rtp_transport_queue_->RunSynchronous([] {});
189 }
190
GetConfig() const191 const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
192 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
193 return config_;
194 }
195
Reconfigure(const webrtc::AudioSendStream::Config & new_config,SetParametersCallback callback)196 void AudioSendStream::Reconfigure(
197 const webrtc::AudioSendStream::Config& new_config,
198 SetParametersCallback callback) {
199 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
200 ConfigureStream(new_config, false, std::move(callback));
201 }
202
FindExtensionIds(const std::vector<RtpExtension> & extensions)203 AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
204 const std::vector<RtpExtension>& extensions) {
205 ExtensionIds ids;
206 for (const auto& extension : extensions) {
207 if (extension.uri == RtpExtension::kAudioLevelUri) {
208 ids.audio_level = extension.id;
209 } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
210 ids.abs_send_time = extension.id;
211 } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
212 ids.transport_sequence_number = extension.id;
213 } else if (extension.uri == RtpExtension::kMidUri) {
214 ids.mid = extension.id;
215 } else if (extension.uri == RtpExtension::kRidUri) {
216 ids.rid = extension.id;
217 } else if (extension.uri == RtpExtension::kRepairedRidUri) {
218 ids.repaired_rid = extension.id;
219 } else if (extension.uri == RtpExtension::kAbsoluteCaptureTimeUri) {
220 ids.abs_capture_time = extension.id;
221 }
222 }
223 return ids;
224 }
225
TransportSeqNumId(const AudioSendStream::Config & config)226 int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
227 return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
228 }
229
ConfigureStream(const webrtc::AudioSendStream::Config & new_config,bool first_time,SetParametersCallback callback)230 void AudioSendStream::ConfigureStream(
231 const webrtc::AudioSendStream::Config& new_config,
232 bool first_time,
233 SetParametersCallback callback) {
234 RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
235 << new_config.ToString();
236 UpdateEventLogStreamConfig(event_log_, new_config,
237 first_time ? nullptr : &config_);
238
239 const auto& old_config = config_;
240
241 // Configuration parameters which cannot be changed.
242 RTC_DCHECK(first_time ||
243 old_config.send_transport == new_config.send_transport);
244 RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
245 if (suspended_rtp_state_ && first_time) {
246 rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
247 }
248 if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
249 channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
250 }
251
252 // Enable the frame encryptor if a new frame encryptor has been provided.
253 if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
254 channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
255 }
256
257 if (first_time ||
258 new_config.frame_transformer != old_config.frame_transformer) {
259 channel_send_->SetEncoderToPacketizerFrameTransformer(
260 new_config.frame_transformer);
261 }
262
263 if (first_time ||
264 new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
265 rtp_rtcp_module_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
266 }
267
268 const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
269 const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
270
271 // Audio level indication
272 if (first_time || new_ids.audio_level != old_ids.audio_level) {
273 channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
274 new_ids.audio_level);
275 }
276
277 if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
278 absl::string_view uri = AbsoluteSendTime::Uri();
279 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(uri);
280 if (new_ids.abs_send_time) {
281 rtp_rtcp_module_->RegisterRtpHeaderExtension(uri, new_ids.abs_send_time);
282 }
283 }
284
285 bool transport_seq_num_id_changed =
286 new_ids.transport_sequence_number != old_ids.transport_sequence_number;
287 if (first_time ||
288 (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
289 if (!first_time) {
290 channel_send_->ResetSenderCongestionControlObjects();
291 }
292
293 RtcpBandwidthObserver* bandwidth_observer = nullptr;
294
295 if (!allocate_audio_without_feedback_ &&
296 new_ids.transport_sequence_number != 0) {
297 rtp_rtcp_module_->RegisterRtpHeaderExtension(
298 TransportSequenceNumber::Uri(), new_ids.transport_sequence_number);
299 // Probing in application limited region is only used in combination with
300 // send side congestion control, wich depends on feedback packets which
301 // requires transport sequence numbers to be enabled.
302 // Optionally request ALR probing but do not override any existing
303 // request from other streams.
304 if (enable_audio_alr_probing_) {
305 rtp_transport_->EnablePeriodicAlrProbing(true);
306 }
307 bandwidth_observer = rtp_transport_->GetBandwidthObserver();
308 }
309 channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
310 bandwidth_observer);
311 }
312 // MID RTP header extension.
313 if ((first_time || new_ids.mid != old_ids.mid ||
314 new_config.rtp.mid != old_config.rtp.mid) &&
315 new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
316 rtp_rtcp_module_->RegisterRtpHeaderExtension(RtpMid::Uri(), new_ids.mid);
317 rtp_rtcp_module_->SetMid(new_config.rtp.mid);
318 }
319
320 if (first_time || new_ids.abs_capture_time != old_ids.abs_capture_time) {
321 absl::string_view uri = AbsoluteCaptureTimeExtension::Uri();
322 rtp_rtcp_module_->DeregisterSendRtpHeaderExtension(uri);
323 if (new_ids.abs_capture_time) {
324 rtp_rtcp_module_->RegisterRtpHeaderExtension(uri,
325 new_ids.abs_capture_time);
326 }
327 }
328
329 if (!ReconfigureSendCodec(new_config)) {
330 RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
331
332 webrtc::InvokeSetParametersCallback(
333 callback, webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR,
334 "Failed to set up send codec state."));
335 }
336
337 // Set currently known overhead (used in ANA, opus only).
338 {
339 MutexLock lock(&overhead_per_packet_lock_);
340 UpdateOverheadForEncoder();
341 }
342
343 channel_send_->CallEncoder([this](AudioEncoder* encoder) {
344 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
345 if (!encoder) {
346 return;
347 }
348 frame_length_range_ = encoder->GetFrameLengthRange();
349 UpdateCachedTargetAudioBitrateConstraints();
350 });
351
352 if (sending_) {
353 ReconfigureBitrateObserver(new_config);
354 }
355
356 config_ = new_config;
357 if (!first_time) {
358 UpdateCachedTargetAudioBitrateConstraints();
359 }
360
361 webrtc::InvokeSetParametersCallback(callback, webrtc::RTCError::OK());
362 }
363
Start()364 void AudioSendStream::Start() {
365 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
366 if (sending_) {
367 return;
368 }
369 if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
370 config_.max_bitrate_bps != -1 &&
371 (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0)) {
372 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
373 rtp_transport_->IncludeOverheadInPacedSender();
374 rtp_rtcp_module_->SetAsPartOfAllocation(true);
375 ConfigureBitrateObserver();
376 } else {
377 rtp_rtcp_module_->SetAsPartOfAllocation(false);
378 }
379 channel_send_->StartSend();
380 sending_ = true;
381 audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
382 encoder_num_channels_);
383 }
384
Stop()385 void AudioSendStream::Stop() {
386 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
387 if (!sending_) {
388 return;
389 }
390
391 RemoveBitrateObserver();
392 channel_send_->StopSend();
393 sending_ = false;
394 audio_state()->RemoveSendingStream(this);
395 }
396
SendAudioData(std::unique_ptr<AudioFrame> audio_frame)397 void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
398 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
399 RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
400 TRACE_EVENT0("webrtc", "AudioSendStream::SendAudioData");
401 double duration = static_cast<double>(audio_frame->samples_per_channel_) /
402 audio_frame->sample_rate_hz_;
403 {
404 // Note: SendAudioData() passes the frame further down the pipeline and it
405 // may eventually get sent. But this method is invoked even if we are not
406 // connected, as long as we have an AudioSendStream (created as a result of
407 // an O/A exchange). This means that we are calculating audio levels whether
408 // or not we are sending samples.
409 // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
410 // should move from send-streams to the local audio sources or tracks; a
411 // send-stream should not be required to read the microphone audio levels.
412 MutexLock lock(&audio_level_lock_);
413 audio_level_.ComputeLevel(*audio_frame, duration);
414 }
415 channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
416 }
417
SendTelephoneEvent(int payload_type,int payload_frequency,int event,int duration_ms)418 bool AudioSendStream::SendTelephoneEvent(int payload_type,
419 int payload_frequency,
420 int event,
421 int duration_ms) {
422 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
423 channel_send_->SetSendTelephoneEventPayloadType(payload_type,
424 payload_frequency);
425 return channel_send_->SendTelephoneEventOutband(event, duration_ms);
426 }
427
SetMuted(bool muted)428 void AudioSendStream::SetMuted(bool muted) {
429 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
430 channel_send_->SetInputMute(muted);
431 }
432
GetStats() const433 webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
434 return GetStats(true);
435 }
436
GetStats(bool has_remote_tracks) const437 webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
438 bool has_remote_tracks) const {
439 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
440 webrtc::AudioSendStream::Stats stats;
441 stats.local_ssrc = config_.rtp.ssrc;
442 stats.target_bitrate_bps = channel_send_->GetTargetBitrate();
443
444 webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
445 stats.payload_bytes_sent = call_stats.payload_bytes_sent;
446 stats.header_and_padding_bytes_sent =
447 call_stats.header_and_padding_bytes_sent;
448 stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
449 stats.packets_sent = call_stats.packetsSent;
450 stats.total_packet_send_delay = call_stats.total_packet_send_delay;
451 stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
452 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
453 // returns 0 to indicate an error value.
454 if (call_stats.rttMs > 0) {
455 stats.rtt_ms = call_stats.rttMs;
456 }
457 if (config_.send_codec_spec) {
458 const auto& spec = *config_.send_codec_spec;
459 stats.codec_name = spec.format.name;
460 stats.codec_payload_type = spec.payload_type;
461
462 // Get data from the last remote RTCP report.
463 for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
464 // Lookup report for send ssrc only.
465 if (block.source_SSRC == stats.local_ssrc) {
466 stats.packets_lost = block.cumulative_num_packets_lost;
467 stats.fraction_lost = Q8ToFloat(block.fraction_lost);
468 // Convert timestamps to milliseconds.
469 if (spec.format.clockrate_hz / 1000 > 0) {
470 stats.jitter_ms =
471 block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
472 }
473 break;
474 }
475 }
476 }
477
478 {
479 MutexLock lock(&audio_level_lock_);
480 stats.audio_level = audio_level_.LevelFullRange();
481 stats.total_input_energy = audio_level_.TotalEnergy();
482 stats.total_input_duration = audio_level_.TotalDuration();
483 }
484
485 stats.ana_statistics = channel_send_->GetANAStatistics();
486
487 AudioProcessing* ap = audio_state_->audio_processing();
488 if (ap) {
489 stats.apm_statistics = ap->GetStatistics(has_remote_tracks);
490 }
491
492 stats.report_block_datas = std::move(call_stats.report_block_datas);
493
494 stats.nacks_rcvd = call_stats.nacks_rcvd;
495
496 return stats;
497 }
498
DeliverRtcp(const uint8_t * packet,size_t length)499 void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
500 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
501 channel_send_->ReceivedRTCPPacket(packet, length);
502
503 {
504 // Poll if overhead has changed, which it can do if ack triggers us to stop
505 // sending mid/rid.
506 MutexLock lock(&overhead_per_packet_lock_);
507 UpdateOverheadForEncoder();
508 }
509 UpdateCachedTargetAudioBitrateConstraints();
510 }
511
OnBitrateUpdated(BitrateAllocationUpdate update)512 uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
513 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
514
515 // Pick a target bitrate between the constraints. Overrules the allocator if
516 // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
517 // higher than max to allow for e.g. extra FEC.
518 RTC_DCHECK(cached_constraints_.has_value());
519 update.target_bitrate.Clamp(cached_constraints_->min,
520 cached_constraints_->max);
521 update.stable_target_bitrate.Clamp(cached_constraints_->min,
522 cached_constraints_->max);
523
524 channel_send_->OnBitrateAllocation(update);
525
526 // The amount of audio protection is not exposed by the encoder, hence
527 // always returning 0.
528 return 0;
529 }
530
SetTransportOverhead(int transport_overhead_per_packet_bytes)531 void AudioSendStream::SetTransportOverhead(
532 int transport_overhead_per_packet_bytes) {
533 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
534 {
535 MutexLock lock(&overhead_per_packet_lock_);
536 transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
537 UpdateOverheadForEncoder();
538 }
539 UpdateCachedTargetAudioBitrateConstraints();
540 }
541
UpdateOverheadForEncoder()542 void AudioSendStream::UpdateOverheadForEncoder() {
543 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
544 size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
545 if (overhead_per_packet_ == overhead_per_packet_bytes) {
546 return;
547 }
548 overhead_per_packet_ = overhead_per_packet_bytes;
549
550 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
551 encoder->OnReceivedOverhead(overhead_per_packet_bytes);
552 });
553 if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
554 total_packet_overhead_bytes_ = overhead_per_packet_bytes;
555 if (registered_with_allocator_) {
556 ConfigureBitrateObserver();
557 }
558 }
559 }
560
TestOnlyGetPerPacketOverheadBytes() const561 size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
562 MutexLock lock(&overhead_per_packet_lock_);
563 return GetPerPacketOverheadBytes();
564 }
565
GetPerPacketOverheadBytes() const566 size_t AudioSendStream::GetPerPacketOverheadBytes() const {
567 return transport_overhead_per_packet_bytes_ +
568 rtp_rtcp_module_->ExpectedPerPacketOverhead();
569 }
570
GetRtpState() const571 RtpState AudioSendStream::GetRtpState() const {
572 return rtp_rtcp_module_->GetRtpState();
573 }
574
GetChannel() const575 const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
576 return channel_send_.get();
577 }
578
audio_state()579 internal::AudioState* AudioSendStream::audio_state() {
580 internal::AudioState* audio_state =
581 static_cast<internal::AudioState*>(audio_state_.get());
582 RTC_DCHECK(audio_state);
583 return audio_state;
584 }
585
audio_state() const586 const internal::AudioState* AudioSendStream::audio_state() const {
587 internal::AudioState* audio_state =
588 static_cast<internal::AudioState*>(audio_state_.get());
589 RTC_DCHECK(audio_state);
590 return audio_state;
591 }
592
StoreEncoderProperties(int sample_rate_hz,size_t num_channels)593 void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
594 size_t num_channels) {
595 encoder_sample_rate_hz_ = sample_rate_hz;
596 encoder_num_channels_ = num_channels;
597 if (sending_) {
598 // Update AudioState's information about the stream.
599 audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
600 }
601 }
602
603 // Apply current codec settings to a single voe::Channel used for sending.
SetupSendCodec(const Config & new_config)604 bool AudioSendStream::SetupSendCodec(const Config& new_config) {
605 RTC_DCHECK(new_config.send_codec_spec);
606 const auto& spec = *new_config.send_codec_spec;
607
608 RTC_DCHECK(new_config.encoder_factory);
609 std::unique_ptr<AudioEncoder> encoder =
610 new_config.encoder_factory->MakeAudioEncoder(
611 spec.payload_type, spec.format, new_config.codec_pair_id);
612
613 if (!encoder) {
614 RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
615 << rtc::ToString(spec.format);
616 return false;
617 }
618
619 // If a bitrate has been specified for the codec, use it over the
620 // codec's default.
621 if (spec.target_bitrate_bps) {
622 encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
623 }
624
625 // Enable ANA if configured (currently only used by Opus).
626 if (new_config.audio_network_adaptor_config) {
627 if (encoder->EnableAudioNetworkAdaptor(
628 *new_config.audio_network_adaptor_config, event_log_)) {
629 RTC_LOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
630 << new_config.rtp.ssrc;
631 } else {
632 RTC_LOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
633 << new_config.rtp.ssrc;
634 }
635 }
636
637 // Wrap the encoder in an AudioEncoderCNG, if VAD is enabled.
638 if (spec.cng_payload_type) {
639 AudioEncoderCngConfig cng_config;
640 cng_config.num_channels = encoder->NumChannels();
641 cng_config.payload_type = *spec.cng_payload_type;
642 cng_config.speech_encoder = std::move(encoder);
643 cng_config.vad_mode = Vad::kVadNormal;
644 encoder = CreateComfortNoiseEncoder(std::move(cng_config));
645
646 RegisterCngPayloadType(*spec.cng_payload_type,
647 new_config.send_codec_spec->format.clockrate_hz);
648 }
649
650 // Wrap the encoder in a RED encoder, if RED is enabled.
651 if (spec.red_payload_type) {
652 AudioEncoderCopyRed::Config red_config;
653 red_config.payload_type = *spec.red_payload_type;
654 red_config.speech_encoder = std::move(encoder);
655 encoder = std::make_unique<AudioEncoderCopyRed>(std::move(red_config),
656 field_trials_);
657 }
658
659 // Set currently known overhead (used in ANA, opus only).
660 // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
661 {
662 MutexLock lock(&overhead_per_packet_lock_);
663 size_t overhead = GetPerPacketOverheadBytes();
664 if (overhead > 0) {
665 encoder->OnReceivedOverhead(overhead);
666 }
667 }
668
669 StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
670 channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
671 std::move(encoder));
672
673 return true;
674 }
675
ReconfigureSendCodec(const Config & new_config)676 bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
677 const auto& old_config = config_;
678
679 if (!new_config.send_codec_spec) {
680 // We cannot de-configure a send codec. So we will do nothing.
681 // By design, the send codec should have not been configured.
682 RTC_DCHECK(!old_config.send_codec_spec);
683 return true;
684 }
685
686 if (new_config.send_codec_spec == old_config.send_codec_spec &&
687 new_config.audio_network_adaptor_config ==
688 old_config.audio_network_adaptor_config) {
689 return true;
690 }
691
692 // If we have no encoder, or the format or payload type's changed, create a
693 // new encoder.
694 if (!old_config.send_codec_spec ||
695 new_config.send_codec_spec->format !=
696 old_config.send_codec_spec->format ||
697 new_config.send_codec_spec->payload_type !=
698 old_config.send_codec_spec->payload_type ||
699 new_config.send_codec_spec->red_payload_type !=
700 old_config.send_codec_spec->red_payload_type) {
701 return SetupSendCodec(new_config);
702 }
703
704 const absl::optional<int>& new_target_bitrate_bps =
705 new_config.send_codec_spec->target_bitrate_bps;
706 // If a bitrate has been specified for the codec, use it over the
707 // codec's default.
708 if (new_target_bitrate_bps &&
709 new_target_bitrate_bps !=
710 old_config.send_codec_spec->target_bitrate_bps) {
711 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
712 encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
713 });
714 }
715
716 ReconfigureANA(new_config);
717 ReconfigureCNG(new_config);
718
719 return true;
720 }
721
ReconfigureANA(const Config & new_config)722 void AudioSendStream::ReconfigureANA(const Config& new_config) {
723 if (new_config.audio_network_adaptor_config ==
724 config_.audio_network_adaptor_config) {
725 return;
726 }
727 if (new_config.audio_network_adaptor_config) {
728 // This lock needs to be acquired before CallEncoder, since it aquires
729 // another lock and we need to maintain the same order at all call sites to
730 // avoid deadlock.
731 MutexLock lock(&overhead_per_packet_lock_);
732 size_t overhead = GetPerPacketOverheadBytes();
733 channel_send_->CallEncoder([&](AudioEncoder* encoder) {
734 if (encoder->EnableAudioNetworkAdaptor(
735 *new_config.audio_network_adaptor_config, event_log_)) {
736 RTC_LOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
737 << new_config.rtp.ssrc;
738 if (overhead > 0) {
739 encoder->OnReceivedOverhead(overhead);
740 }
741 } else {
742 RTC_LOG(LS_INFO) << "Failed to enable Audio network adaptor on SSRC "
743 << new_config.rtp.ssrc;
744 }
745 });
746 } else {
747 channel_send_->CallEncoder(
748 [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
749 RTC_LOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
750 << new_config.rtp.ssrc;
751 }
752 }
753
ReconfigureCNG(const Config & new_config)754 void AudioSendStream::ReconfigureCNG(const Config& new_config) {
755 if (new_config.send_codec_spec->cng_payload_type ==
756 config_.send_codec_spec->cng_payload_type) {
757 return;
758 }
759
760 // Register the CNG payload type if it's been added, don't do anything if CNG
761 // is removed. Payload types must not be redefined.
762 if (new_config.send_codec_spec->cng_payload_type) {
763 RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
764 new_config.send_codec_spec->format.clockrate_hz);
765 }
766
767 // Wrap or unwrap the encoder in an AudioEncoderCNG.
768 channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
769 std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
770 auto sub_encoders = old_encoder->ReclaimContainedEncoders();
771 if (!sub_encoders.empty()) {
772 // Replace enc with its sub encoder. We need to put the sub
773 // encoder in a temporary first, since otherwise the old value
774 // of enc would be destroyed before the new value got assigned,
775 // which would be bad since the new value is a part of the old
776 // value.
777 auto tmp = std::move(sub_encoders[0]);
778 old_encoder = std::move(tmp);
779 }
780 if (new_config.send_codec_spec->cng_payload_type) {
781 AudioEncoderCngConfig config;
782 config.speech_encoder = std::move(old_encoder);
783 config.num_channels = config.speech_encoder->NumChannels();
784 config.payload_type = *new_config.send_codec_spec->cng_payload_type;
785 config.vad_mode = Vad::kVadNormal;
786 *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
787 } else {
788 *encoder_ptr = std::move(old_encoder);
789 }
790 });
791 }
792
ReconfigureBitrateObserver(const webrtc::AudioSendStream::Config & new_config)793 void AudioSendStream::ReconfigureBitrateObserver(
794 const webrtc::AudioSendStream::Config& new_config) {
795 // Since the Config's default is for both of these to be -1, this test will
796 // allow us to configure the bitrate observer if the new config has bitrate
797 // limits set, but would only have us call RemoveBitrateObserver if we were
798 // previously configured with bitrate limits.
799 if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
800 config_.max_bitrate_bps == new_config.max_bitrate_bps &&
801 config_.bitrate_priority == new_config.bitrate_priority &&
802 TransportSeqNumId(config_) == TransportSeqNumId(new_config) &&
803 config_.audio_network_adaptor_config ==
804 new_config.audio_network_adaptor_config) {
805 return;
806 }
807
808 if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
809 new_config.max_bitrate_bps != -1 && TransportSeqNumId(new_config) != 0) {
810 rtp_transport_->AccountForAudioPacketsInPacedSender(true);
811 rtp_transport_->IncludeOverheadInPacedSender();
812 // We may get a callback immediately as the observer is registered, so
813 // make sure the bitrate limits in config_ are up-to-date.
814 config_.min_bitrate_bps = new_config.min_bitrate_bps;
815 config_.max_bitrate_bps = new_config.max_bitrate_bps;
816
817 config_.bitrate_priority = new_config.bitrate_priority;
818 ConfigureBitrateObserver();
819 rtp_rtcp_module_->SetAsPartOfAllocation(true);
820 } else {
821 rtp_transport_->AccountForAudioPacketsInPacedSender(false);
822 RemoveBitrateObserver();
823 rtp_rtcp_module_->SetAsPartOfAllocation(false);
824 }
825 }
826
ConfigureBitrateObserver()827 void AudioSendStream::ConfigureBitrateObserver() {
828 // This either updates the current observer or adds a new observer.
829 // TODO(srte): Add overhead compensation here.
830 auto constraints = GetMinMaxBitrateConstraints();
831 RTC_DCHECK(constraints.has_value());
832
833 DataRate priority_bitrate = allocation_settings_.priority_bitrate;
834 if (use_legacy_overhead_calculation_) {
835 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
836 constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
837 const TimeDelta kMinPacketDuration = TimeDelta::Millis(20);
838 DataRate max_overhead =
839 DataSize::Bytes(kOverheadPerPacket) / kMinPacketDuration;
840 priority_bitrate += max_overhead;
841 } else {
842 RTC_DCHECK(frame_length_range_);
843 const DataSize overhead_per_packet =
844 DataSize::Bytes(total_packet_overhead_bytes_);
845 DataRate min_overhead = overhead_per_packet / frame_length_range_->second;
846 priority_bitrate += min_overhead;
847 }
848
849 if (allocation_settings_.priority_bitrate_raw)
850 priority_bitrate = *allocation_settings_.priority_bitrate_raw;
851
852 rtp_transport_queue_->RunOrPost([this, constraints, priority_bitrate,
853 config_bitrate_priority =
854 config_.bitrate_priority] {
855 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
856 bitrate_allocator_->AddObserver(
857 this,
858 MediaStreamAllocationConfig{
859 constraints->min.bps<uint32_t>(), constraints->max.bps<uint32_t>(),
860 0, priority_bitrate.bps(), true,
861 allocation_settings_.bitrate_priority.value_or(
862 config_bitrate_priority)});
863 });
864 registered_with_allocator_ = true;
865 }
866
RemoveBitrateObserver()867 void AudioSendStream::RemoveBitrateObserver() {
868 registered_with_allocator_ = false;
869 rtp_transport_queue_->RunSynchronous([this] {
870 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
871 bitrate_allocator_->RemoveObserver(this);
872 });
873 }
874
875 absl::optional<AudioSendStream::TargetAudioBitrateConstraints>
GetMinMaxBitrateConstraints() const876 AudioSendStream::GetMinMaxBitrateConstraints() const {
877 if (config_.min_bitrate_bps < 0 || config_.max_bitrate_bps < 0) {
878 RTC_LOG(LS_WARNING) << "Config is invalid: min_bitrate_bps="
879 << config_.min_bitrate_bps
880 << "; max_bitrate_bps=" << config_.max_bitrate_bps
881 << "; both expected greater or equal to 0";
882 return absl::nullopt;
883 }
884 TargetAudioBitrateConstraints constraints{
885 DataRate::BitsPerSec(config_.min_bitrate_bps),
886 DataRate::BitsPerSec(config_.max_bitrate_bps)};
887
888 // If bitrates were explicitly overriden via field trial, use those values.
889 if (allocation_settings_.min_bitrate)
890 constraints.min = *allocation_settings_.min_bitrate;
891 if (allocation_settings_.max_bitrate)
892 constraints.max = *allocation_settings_.max_bitrate;
893
894 RTC_DCHECK_GE(constraints.min, DataRate::Zero());
895 RTC_DCHECK_GE(constraints.max, DataRate::Zero());
896 if (constraints.max < constraints.min) {
897 RTC_LOG(LS_WARNING) << "TargetAudioBitrateConstraints::max is less than "
898 << "TargetAudioBitrateConstraints::min";
899 return absl::nullopt;
900 }
901 if (use_legacy_overhead_calculation_) {
902 // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
903 const DataSize kOverheadPerPacket = DataSize::Bytes(20 + 8 + 10 + 12);
904 const TimeDelta kMaxFrameLength =
905 TimeDelta::Millis(60); // Based on Opus spec
906 const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
907 constraints.min += kMinOverhead;
908 constraints.max += kMinOverhead;
909 } else {
910 if (!frame_length_range_.has_value()) {
911 RTC_LOG(LS_WARNING) << "frame_length_range_ is not set";
912 return absl::nullopt;
913 }
914 const DataSize kOverheadPerPacket =
915 DataSize::Bytes(total_packet_overhead_bytes_);
916 constraints.min += kOverheadPerPacket / frame_length_range_->second;
917 constraints.max += kOverheadPerPacket / frame_length_range_->first;
918 }
919 return constraints;
920 }
921
RegisterCngPayloadType(int payload_type,int clockrate_hz)922 void AudioSendStream::RegisterCngPayloadType(int payload_type,
923 int clockrate_hz) {
924 channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
925 }
926
UpdateCachedTargetAudioBitrateConstraints()927 void AudioSendStream::UpdateCachedTargetAudioBitrateConstraints() {
928 absl::optional<AudioSendStream::TargetAudioBitrateConstraints>
929 new_constraints = GetMinMaxBitrateConstraints();
930 if (!new_constraints.has_value()) {
931 return;
932 }
933 rtp_transport_queue_->RunOrPost([this, new_constraints]() {
934 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
935 cached_constraints_ = new_constraints;
936 });
937 }
938
939 } // namespace internal
940 } // namespace webrtc
941