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