Niels Möller | 530ead4 | 2018-10-04 14:28:39 +0200 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2012 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/channel_send.h" |
| 12 | |
| 13 | #include <algorithm> |
| 14 | #include <map> |
| 15 | #include <memory> |
| 16 | #include <string> |
| 17 | #include <utility> |
| 18 | #include <vector> |
| 19 | |
| 20 | #include "absl/memory/memory.h" |
| 21 | #include "api/array_view.h" |
| 22 | #include "audio/utility/audio_frame_operations.h" |
| 23 | #include "call/rtp_transport_controller_send_interface.h" |
| 24 | #include "logging/rtc_event_log/events/rtc_event_audio_playout.h" |
| 25 | #include "logging/rtc_event_log/rtc_event_log.h" |
| 26 | #include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h" |
| 27 | #include "modules/pacing/packet_router.h" |
| 28 | #include "modules/utility/include/process_thread.h" |
| 29 | #include "rtc_base/checks.h" |
| 30 | #include "rtc_base/criticalsection.h" |
| 31 | #include "rtc_base/format_macros.h" |
| 32 | #include "rtc_base/location.h" |
| 33 | #include "rtc_base/logging.h" |
| 34 | #include "rtc_base/rate_limiter.h" |
| 35 | #include "rtc_base/task_queue.h" |
| 36 | #include "rtc_base/thread_checker.h" |
| 37 | #include "rtc_base/timeutils.h" |
| 38 | #include "system_wrappers/include/field_trial.h" |
| 39 | #include "system_wrappers/include/metrics.h" |
| 40 | |
| 41 | namespace webrtc { |
| 42 | namespace voe { |
| 43 | |
| 44 | namespace { |
| 45 | |
| 46 | constexpr int64_t kMaxRetransmissionWindowMs = 1000; |
| 47 | constexpr int64_t kMinRetransmissionWindowMs = 30; |
| 48 | |
| 49 | } // namespace |
| 50 | |
| 51 | const int kTelephoneEventAttenuationdB = 10; |
| 52 | |
| 53 | class TransportFeedbackProxy : public TransportFeedbackObserver { |
| 54 | public: |
| 55 | TransportFeedbackProxy() : feedback_observer_(nullptr) { |
| 56 | pacer_thread_.DetachFromThread(); |
| 57 | network_thread_.DetachFromThread(); |
| 58 | } |
| 59 | |
| 60 | void SetTransportFeedbackObserver( |
| 61 | TransportFeedbackObserver* feedback_observer) { |
| 62 | RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 63 | rtc::CritScope lock(&crit_); |
| 64 | feedback_observer_ = feedback_observer; |
| 65 | } |
| 66 | |
| 67 | // Implements TransportFeedbackObserver. |
| 68 | void AddPacket(uint32_t ssrc, |
| 69 | uint16_t sequence_number, |
| 70 | size_t length, |
| 71 | const PacedPacketInfo& pacing_info) override { |
| 72 | RTC_DCHECK(pacer_thread_.CalledOnValidThread()); |
| 73 | rtc::CritScope lock(&crit_); |
| 74 | if (feedback_observer_) |
| 75 | feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info); |
| 76 | } |
| 77 | |
| 78 | void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override { |
| 79 | RTC_DCHECK(network_thread_.CalledOnValidThread()); |
| 80 | rtc::CritScope lock(&crit_); |
| 81 | if (feedback_observer_) |
| 82 | feedback_observer_->OnTransportFeedback(feedback); |
| 83 | } |
| 84 | |
| 85 | private: |
| 86 | rtc::CriticalSection crit_; |
| 87 | rtc::ThreadChecker thread_checker_; |
| 88 | rtc::ThreadChecker pacer_thread_; |
| 89 | rtc::ThreadChecker network_thread_; |
| 90 | TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_); |
| 91 | }; |
| 92 | |
| 93 | class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator { |
| 94 | public: |
| 95 | TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) { |
| 96 | pacer_thread_.DetachFromThread(); |
| 97 | } |
| 98 | |
| 99 | void SetSequenceNumberAllocator( |
| 100 | TransportSequenceNumberAllocator* seq_num_allocator) { |
| 101 | RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 102 | rtc::CritScope lock(&crit_); |
| 103 | seq_num_allocator_ = seq_num_allocator; |
| 104 | } |
| 105 | |
| 106 | // Implements TransportSequenceNumberAllocator. |
| 107 | uint16_t AllocateSequenceNumber() override { |
| 108 | RTC_DCHECK(pacer_thread_.CalledOnValidThread()); |
| 109 | rtc::CritScope lock(&crit_); |
| 110 | if (!seq_num_allocator_) |
| 111 | return 0; |
| 112 | return seq_num_allocator_->AllocateSequenceNumber(); |
| 113 | } |
| 114 | |
| 115 | private: |
| 116 | rtc::CriticalSection crit_; |
| 117 | rtc::ThreadChecker thread_checker_; |
| 118 | rtc::ThreadChecker pacer_thread_; |
| 119 | TransportSequenceNumberAllocator* seq_num_allocator_ RTC_GUARDED_BY(&crit_); |
| 120 | }; |
| 121 | |
| 122 | class RtpPacketSenderProxy : public RtpPacketSender { |
| 123 | public: |
| 124 | RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {} |
| 125 | |
| 126 | void SetPacketSender(RtpPacketSender* rtp_packet_sender) { |
| 127 | RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 128 | rtc::CritScope lock(&crit_); |
| 129 | rtp_packet_sender_ = rtp_packet_sender; |
| 130 | } |
| 131 | |
| 132 | // Implements RtpPacketSender. |
| 133 | void InsertPacket(Priority priority, |
| 134 | uint32_t ssrc, |
| 135 | uint16_t sequence_number, |
| 136 | int64_t capture_time_ms, |
| 137 | size_t bytes, |
| 138 | bool retransmission) override { |
| 139 | rtc::CritScope lock(&crit_); |
| 140 | if (rtp_packet_sender_) { |
| 141 | rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number, |
| 142 | capture_time_ms, bytes, retransmission); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | void SetAccountForAudioPackets(bool account_for_audio) override { |
| 147 | RTC_NOTREACHED(); |
| 148 | } |
| 149 | |
| 150 | private: |
| 151 | rtc::ThreadChecker thread_checker_; |
| 152 | rtc::CriticalSection crit_; |
| 153 | RtpPacketSender* rtp_packet_sender_ RTC_GUARDED_BY(&crit_); |
| 154 | }; |
| 155 | |
| 156 | class VoERtcpObserver : public RtcpBandwidthObserver { |
| 157 | public: |
| 158 | explicit VoERtcpObserver(ChannelSend* owner) |
| 159 | : owner_(owner), bandwidth_observer_(nullptr) {} |
| 160 | virtual ~VoERtcpObserver() {} |
| 161 | |
| 162 | void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) { |
| 163 | rtc::CritScope lock(&crit_); |
| 164 | bandwidth_observer_ = bandwidth_observer; |
| 165 | } |
| 166 | |
| 167 | void OnReceivedEstimatedBitrate(uint32_t bitrate) override { |
| 168 | rtc::CritScope lock(&crit_); |
| 169 | if (bandwidth_observer_) { |
| 170 | bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks, |
| 175 | int64_t rtt, |
| 176 | int64_t now_ms) override { |
| 177 | { |
| 178 | rtc::CritScope lock(&crit_); |
| 179 | if (bandwidth_observer_) { |
| 180 | bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt, |
| 181 | now_ms); |
| 182 | } |
| 183 | } |
| 184 | // TODO(mflodman): Do we need to aggregate reports here or can we jut send |
| 185 | // what we get? I.e. do we ever get multiple reports bundled into one RTCP |
| 186 | // report for VoiceEngine? |
| 187 | if (report_blocks.empty()) |
| 188 | return; |
| 189 | |
| 190 | int fraction_lost_aggregate = 0; |
| 191 | int total_number_of_packets = 0; |
| 192 | |
| 193 | // If receiving multiple report blocks, calculate the weighted average based |
| 194 | // on the number of packets a report refers to. |
| 195 | for (ReportBlockList::const_iterator block_it = report_blocks.begin(); |
| 196 | block_it != report_blocks.end(); ++block_it) { |
| 197 | // Find the previous extended high sequence number for this remote SSRC, |
| 198 | // to calculate the number of RTP packets this report refers to. Ignore if |
| 199 | // we haven't seen this SSRC before. |
| 200 | std::map<uint32_t, uint32_t>::iterator seq_num_it = |
| 201 | extended_max_sequence_number_.find(block_it->source_ssrc); |
| 202 | int number_of_packets = 0; |
| 203 | if (seq_num_it != extended_max_sequence_number_.end()) { |
| 204 | number_of_packets = |
| 205 | block_it->extended_highest_sequence_number - seq_num_it->second; |
| 206 | } |
| 207 | fraction_lost_aggregate += number_of_packets * block_it->fraction_lost; |
| 208 | total_number_of_packets += number_of_packets; |
| 209 | |
| 210 | extended_max_sequence_number_[block_it->source_ssrc] = |
| 211 | block_it->extended_highest_sequence_number; |
| 212 | } |
| 213 | int weighted_fraction_lost = 0; |
| 214 | if (total_number_of_packets > 0) { |
| 215 | weighted_fraction_lost = |
| 216 | (fraction_lost_aggregate + total_number_of_packets / 2) / |
| 217 | total_number_of_packets; |
| 218 | } |
| 219 | owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f); |
| 220 | } |
| 221 | |
| 222 | private: |
| 223 | ChannelSend* owner_; |
| 224 | // Maps remote side ssrc to extended highest sequence number received. |
| 225 | std::map<uint32_t, uint32_t> extended_max_sequence_number_; |
| 226 | rtc::CriticalSection crit_; |
| 227 | RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_); |
| 228 | }; |
| 229 | |
| 230 | class ChannelSend::ProcessAndEncodeAudioTask : public rtc::QueuedTask { |
| 231 | public: |
| 232 | ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame, |
| 233 | ChannelSend* channel) |
| 234 | : audio_frame_(std::move(audio_frame)), channel_(channel) { |
| 235 | RTC_DCHECK(channel_); |
| 236 | } |
| 237 | |
| 238 | private: |
| 239 | bool Run() override { |
| 240 | RTC_DCHECK_RUN_ON(channel_->encoder_queue_); |
| 241 | channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get()); |
| 242 | return true; |
| 243 | } |
| 244 | |
| 245 | std::unique_ptr<AudioFrame> audio_frame_; |
| 246 | ChannelSend* const channel_; |
| 247 | }; |
| 248 | |
| 249 | int32_t ChannelSend::SendData(FrameType frameType, |
| 250 | uint8_t payloadType, |
| 251 | uint32_t timeStamp, |
| 252 | const uint8_t* payloadData, |
| 253 | size_t payloadSize, |
| 254 | const RTPFragmentationHeader* fragmentation) { |
| 255 | RTC_DCHECK_RUN_ON(encoder_queue_); |
| 256 | if (_includeAudioLevelIndication) { |
| 257 | // Store current audio level in the RTP/RTCP module. |
| 258 | // The level will be used in combination with voice-activity state |
| 259 | // (frameType) to add an RTP header extension |
| 260 | _rtpRtcpModule->SetAudioLevel(rms_level_.Average()); |
| 261 | } |
| 262 | |
| 263 | // Push data from ACM to RTP/RTCP-module to deliver audio frame for |
| 264 | // packetization. |
| 265 | // This call will trigger Transport::SendPacket() from the RTP/RTCP module. |
| 266 | if (!_rtpRtcpModule->SendOutgoingData( |
| 267 | (FrameType&)frameType, payloadType, timeStamp, |
| 268 | // Leaving the time when this frame was |
| 269 | // received from the capture device as |
| 270 | // undefined for voice for now. |
| 271 | -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) { |
| 272 | RTC_DLOG(LS_ERROR) |
| 273 | << "ChannelSend::SendData() failed to send data to RTP/RTCP module"; |
| 274 | return -1; |
| 275 | } |
| 276 | |
| 277 | return 0; |
| 278 | } |
| 279 | |
| 280 | bool ChannelSend::SendRtp(const uint8_t* data, |
| 281 | size_t len, |
| 282 | const PacketOptions& options) { |
| 283 | rtc::CritScope cs(&_callbackCritSect); |
| 284 | |
| 285 | if (_transportPtr == NULL) { |
| 286 | RTC_DLOG(LS_ERROR) |
| 287 | << "ChannelSend::SendPacket() failed to send RTP packet due to" |
| 288 | << " invalid transport object"; |
| 289 | return false; |
| 290 | } |
| 291 | |
| 292 | if (!_transportPtr->SendRtp(data, len, options)) { |
| 293 | RTC_DLOG(LS_ERROR) << "ChannelSend::SendPacket() RTP transmission failed"; |
| 294 | return false; |
| 295 | } |
| 296 | return true; |
| 297 | } |
| 298 | |
| 299 | bool ChannelSend::SendRtcp(const uint8_t* data, size_t len) { |
| 300 | rtc::CritScope cs(&_callbackCritSect); |
| 301 | if (_transportPtr == NULL) { |
| 302 | RTC_DLOG(LS_ERROR) |
| 303 | << "ChannelSend::SendRtcp() failed to send RTCP packet due to" |
| 304 | << " invalid transport object"; |
| 305 | return false; |
| 306 | } |
| 307 | |
| 308 | int n = _transportPtr->SendRtcp(data, len); |
| 309 | if (n < 0) { |
| 310 | RTC_DLOG(LS_ERROR) << "ChannelSend::SendRtcp() transmission failed"; |
| 311 | return false; |
| 312 | } |
| 313 | return true; |
| 314 | } |
| 315 | |
| 316 | int ChannelSend::PreferredSampleRate() const { |
| 317 | // Return the bigger of playout and receive frequency in the ACM. |
| 318 | return std::max(audio_coding_->ReceiveFrequency(), |
| 319 | audio_coding_->PlayoutFrequency()); |
| 320 | } |
| 321 | |
| 322 | ChannelSend::ChannelSend(rtc::TaskQueue* encoder_queue, |
| 323 | ProcessThread* module_process_thread, |
| 324 | RtcpRttStats* rtcp_rtt_stats, |
| 325 | RtcEventLog* rtc_event_log) |
| 326 | : event_log_(rtc_event_log), |
| 327 | _timeStamp(0), // This is just an offset, RTP module will add it's own |
| 328 | // random offset |
| 329 | send_sequence_number_(0), |
| 330 | _moduleProcessThreadPtr(module_process_thread), |
| 331 | _transportPtr(NULL), |
| 332 | input_mute_(false), |
| 333 | previous_frame_muted_(false), |
| 334 | _includeAudioLevelIndication(false), |
| 335 | transport_overhead_per_packet_(0), |
| 336 | rtp_overhead_per_packet_(0), |
| 337 | rtcp_observer_(new VoERtcpObserver(this)), |
| 338 | feedback_observer_proxy_(new TransportFeedbackProxy()), |
| 339 | seq_num_allocator_proxy_(new TransportSequenceNumberProxy()), |
| 340 | rtp_packet_sender_proxy_(new RtpPacketSenderProxy()), |
| 341 | retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(), |
| 342 | kMaxRetransmissionWindowMs)), |
| 343 | use_twcc_plr_for_ana_( |
| 344 | webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled"), |
| 345 | encoder_queue_(encoder_queue) { |
| 346 | RTC_DCHECK(module_process_thread); |
| 347 | RTC_DCHECK(encoder_queue); |
| 348 | audio_coding_.reset(AudioCodingModule::Create(AudioCodingModule::Config())); |
| 349 | |
| 350 | RtpRtcp::Configuration configuration; |
| 351 | configuration.audio = true; |
| 352 | configuration.outgoing_transport = this; |
| 353 | configuration.overhead_observer = this; |
| 354 | configuration.bandwidth_callback = rtcp_observer_.get(); |
| 355 | |
| 356 | configuration.paced_sender = rtp_packet_sender_proxy_.get(); |
| 357 | configuration.transport_sequence_number_allocator = |
| 358 | seq_num_allocator_proxy_.get(); |
| 359 | configuration.transport_feedback_callback = feedback_observer_proxy_.get(); |
| 360 | |
| 361 | configuration.event_log = event_log_; |
| 362 | configuration.rtt_stats = rtcp_rtt_stats; |
| 363 | configuration.retransmission_rate_limiter = |
| 364 | retransmission_rate_limiter_.get(); |
| 365 | |
| 366 | _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration)); |
| 367 | _rtpRtcpModule->SetSendingMediaStatus(false); |
| 368 | Init(); |
| 369 | } |
| 370 | |
| 371 | ChannelSend::~ChannelSend() { |
| 372 | Terminate(); |
| 373 | RTC_DCHECK(!channel_state_.Get().sending); |
| 374 | } |
| 375 | |
| 376 | void ChannelSend::Init() { |
| 377 | channel_state_.Reset(); |
| 378 | |
| 379 | // --- Add modules to process thread (for periodic schedulation) |
| 380 | _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE); |
| 381 | |
| 382 | // --- ACM initialization |
| 383 | int error = audio_coding_->InitializeReceiver(); |
| 384 | RTC_DCHECK_EQ(0, error); |
| 385 | |
| 386 | // --- RTP/RTCP module initialization |
| 387 | |
| 388 | // Ensure that RTCP is enabled by default for the created channel. |
| 389 | // Note that, the module will keep generating RTCP until it is explicitly |
| 390 | // disabled by the user. |
| 391 | // After StopListen (when no sockets exists), RTCP packets will no longer |
| 392 | // be transmitted since the Transport object will then be invalid. |
| 393 | // RTCP is enabled by default. |
| 394 | _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound); |
| 395 | |
| 396 | // --- Register all permanent callbacks |
| 397 | error = audio_coding_->RegisterTransportCallback(this); |
| 398 | RTC_DCHECK_EQ(0, error); |
| 399 | } |
| 400 | |
| 401 | void ChannelSend::Terminate() { |
| 402 | RTC_DCHECK(construction_thread_.CalledOnValidThread()); |
| 403 | // Must be called on the same thread as Init(). |
| 404 | |
| 405 | StopSend(); |
| 406 | |
| 407 | // The order to safely shutdown modules in a channel is: |
| 408 | // 1. De-register callbacks in modules |
| 409 | // 2. De-register modules in process thread |
| 410 | // 3. Destroy modules |
| 411 | int error = audio_coding_->RegisterTransportCallback(NULL); |
| 412 | RTC_DCHECK_EQ(0, error); |
| 413 | |
| 414 | // De-register modules in process thread |
| 415 | if (_moduleProcessThreadPtr) |
| 416 | _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get()); |
| 417 | |
| 418 | // End of modules shutdown |
| 419 | } |
| 420 | |
| 421 | int32_t ChannelSend::StartSend() { |
| 422 | if (channel_state_.Get().sending) { |
| 423 | return 0; |
| 424 | } |
| 425 | channel_state_.SetSending(true); |
| 426 | |
| 427 | // Resume the previous sequence number which was reset by StopSend(). This |
| 428 | // needs to be done before |sending| is set to true on the RTP/RTCP module. |
| 429 | if (send_sequence_number_) { |
| 430 | _rtpRtcpModule->SetSequenceNumber(send_sequence_number_); |
| 431 | } |
| 432 | _rtpRtcpModule->SetSendingMediaStatus(true); |
| 433 | if (_rtpRtcpModule->SetSendingStatus(true) != 0) { |
| 434 | RTC_DLOG(LS_ERROR) << "StartSend() RTP/RTCP failed to start sending"; |
| 435 | _rtpRtcpModule->SetSendingMediaStatus(false); |
| 436 | rtc::CritScope cs(&_callbackCritSect); |
| 437 | channel_state_.SetSending(false); |
| 438 | return -1; |
| 439 | } |
| 440 | { |
| 441 | // It is now OK to start posting tasks to the encoder task queue. |
| 442 | rtc::CritScope cs(&encoder_queue_lock_); |
| 443 | encoder_queue_is_active_ = true; |
| 444 | } |
| 445 | return 0; |
| 446 | } |
| 447 | |
| 448 | void ChannelSend::StopSend() { |
| 449 | if (!channel_state_.Get().sending) { |
| 450 | return; |
| 451 | } |
| 452 | channel_state_.SetSending(false); |
| 453 | |
| 454 | // Post a task to the encoder thread which sets an event when the task is |
| 455 | // executed. We know that no more encoding tasks will be added to the task |
| 456 | // queue for this channel since sending is now deactivated. It means that, |
| 457 | // if we wait for the event to bet set, we know that no more pending tasks |
| 458 | // exists and it is therfore guaranteed that the task queue will never try |
| 459 | // to acccess and invalid channel object. |
| 460 | RTC_DCHECK(encoder_queue_); |
| 461 | |
| 462 | rtc::Event flush(false, false); |
| 463 | { |
| 464 | // Clear |encoder_queue_is_active_| under lock to prevent any other tasks |
| 465 | // than this final "flush task" to be posted on the queue. |
| 466 | rtc::CritScope cs(&encoder_queue_lock_); |
| 467 | encoder_queue_is_active_ = false; |
| 468 | encoder_queue_->PostTask([&flush]() { flush.Set(); }); |
| 469 | } |
| 470 | flush.Wait(rtc::Event::kForever); |
| 471 | |
| 472 | // Store the sequence number to be able to pick up the same sequence for |
| 473 | // the next StartSend(). This is needed for restarting device, otherwise |
| 474 | // it might cause libSRTP to complain about packets being replayed. |
| 475 | // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring |
| 476 | // CL is landed. See issue |
| 477 | // https://code.google.com/p/webrtc/issues/detail?id=2111 . |
| 478 | send_sequence_number_ = _rtpRtcpModule->SequenceNumber(); |
| 479 | |
| 480 | // Reset sending SSRC and sequence number and triggers direct transmission |
| 481 | // of RTCP BYE |
| 482 | if (_rtpRtcpModule->SetSendingStatus(false) == -1) { |
| 483 | RTC_DLOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending"; |
| 484 | } |
| 485 | _rtpRtcpModule->SetSendingMediaStatus(false); |
| 486 | } |
| 487 | |
| 488 | bool ChannelSend::SetEncoder(int payload_type, |
| 489 | std::unique_ptr<AudioEncoder> encoder) { |
| 490 | RTC_DCHECK_GE(payload_type, 0); |
| 491 | RTC_DCHECK_LE(payload_type, 127); |
| 492 | // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and |
| 493 | // one for for us to keep track of sample rate and number of channels, etc. |
| 494 | |
| 495 | // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate) |
| 496 | // as well as some other things, so we collect this info and send it along. |
| 497 | CodecInst rtp_codec; |
| 498 | rtp_codec.pltype = payload_type; |
| 499 | strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname)); |
| 500 | rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0; |
| 501 | // Seems unclear if it should be clock rate or sample rate. CodecInst |
| 502 | // supposedly carries the sample rate, but only clock rate seems sensible to |
| 503 | // send to the RTP/RTCP module. |
| 504 | rtp_codec.plfreq = encoder->RtpTimestampRateHz(); |
| 505 | rtp_codec.pacsize = rtc::CheckedDivExact( |
| 506 | static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq), |
| 507 | 100); |
| 508 | rtp_codec.channels = encoder->NumChannels(); |
| 509 | rtp_codec.rate = 0; |
| 510 | |
| 511 | if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) { |
| 512 | _rtpRtcpModule->DeRegisterSendPayload(payload_type); |
| 513 | if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) { |
| 514 | RTC_DLOG(LS_ERROR) |
| 515 | << "SetEncoder() failed to register codec to RTP/RTCP module"; |
| 516 | return false; |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | audio_coding_->SetEncoder(std::move(encoder)); |
| 521 | return true; |
| 522 | } |
| 523 | |
| 524 | void ChannelSend::ModifyEncoder( |
| 525 | rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) { |
| 526 | audio_coding_->ModifyEncoder(modifier); |
| 527 | } |
| 528 | |
| 529 | void ChannelSend::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) { |
| 530 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 531 | if (*encoder) { |
| 532 | (*encoder)->OnReceivedUplinkBandwidth(bitrate_bps, probing_interval_ms); |
| 533 | } |
| 534 | }); |
| 535 | retransmission_rate_limiter_->SetMaxRate(bitrate_bps); |
| 536 | } |
| 537 | |
| 538 | void ChannelSend::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) { |
| 539 | if (!use_twcc_plr_for_ana_) |
| 540 | return; |
| 541 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 542 | if (*encoder) { |
| 543 | (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate); |
| 544 | } |
| 545 | }); |
| 546 | } |
| 547 | |
| 548 | void ChannelSend::OnRecoverableUplinkPacketLossRate( |
| 549 | float recoverable_packet_loss_rate) { |
| 550 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 551 | if (*encoder) { |
| 552 | (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction( |
| 553 | recoverable_packet_loss_rate); |
| 554 | } |
| 555 | }); |
| 556 | } |
| 557 | |
| 558 | void ChannelSend::OnUplinkPacketLossRate(float packet_loss_rate) { |
| 559 | if (use_twcc_plr_for_ana_) |
| 560 | return; |
| 561 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 562 | if (*encoder) { |
| 563 | (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate); |
| 564 | } |
| 565 | }); |
| 566 | } |
| 567 | |
| 568 | bool ChannelSend::EnableAudioNetworkAdaptor(const std::string& config_string) { |
| 569 | bool success = false; |
| 570 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 571 | if (*encoder) { |
| 572 | success = |
| 573 | (*encoder)->EnableAudioNetworkAdaptor(config_string, event_log_); |
| 574 | } |
| 575 | }); |
| 576 | return success; |
| 577 | } |
| 578 | |
| 579 | void ChannelSend::DisableAudioNetworkAdaptor() { |
| 580 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 581 | if (*encoder) |
| 582 | (*encoder)->DisableAudioNetworkAdaptor(); |
| 583 | }); |
| 584 | } |
| 585 | |
| 586 | void ChannelSend::SetReceiverFrameLengthRange(int min_frame_length_ms, |
| 587 | int max_frame_length_ms) { |
| 588 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 589 | if (*encoder) { |
| 590 | (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms, |
| 591 | max_frame_length_ms); |
| 592 | } |
| 593 | }); |
| 594 | } |
| 595 | |
| 596 | void ChannelSend::RegisterTransport(Transport* transport) { |
| 597 | rtc::CritScope cs(&_callbackCritSect); |
| 598 | _transportPtr = transport; |
| 599 | } |
| 600 | |
| 601 | int32_t ChannelSend::ReceivedRTCPPacket(const uint8_t* data, size_t length) { |
| 602 | // Deliver RTCP packet to RTP/RTCP module for parsing |
| 603 | _rtpRtcpModule->IncomingRtcpPacket(data, length); |
| 604 | |
| 605 | int64_t rtt = GetRTT(); |
| 606 | if (rtt == 0) { |
| 607 | // Waiting for valid RTT. |
| 608 | return 0; |
| 609 | } |
| 610 | |
| 611 | int64_t nack_window_ms = rtt; |
| 612 | if (nack_window_ms < kMinRetransmissionWindowMs) { |
| 613 | nack_window_ms = kMinRetransmissionWindowMs; |
| 614 | } else if (nack_window_ms > kMaxRetransmissionWindowMs) { |
| 615 | nack_window_ms = kMaxRetransmissionWindowMs; |
| 616 | } |
| 617 | retransmission_rate_limiter_->SetWindowSize(nack_window_ms); |
| 618 | |
| 619 | // Invoke audio encoders OnReceivedRtt(). |
| 620 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 621 | if (*encoder) |
| 622 | (*encoder)->OnReceivedRtt(rtt); |
| 623 | }); |
| 624 | |
| 625 | return 0; |
| 626 | } |
| 627 | |
| 628 | void ChannelSend::SetInputMute(bool enable) { |
| 629 | rtc::CritScope cs(&volume_settings_critsect_); |
| 630 | input_mute_ = enable; |
| 631 | } |
| 632 | |
| 633 | bool ChannelSend::InputMute() const { |
| 634 | rtc::CritScope cs(&volume_settings_critsect_); |
| 635 | return input_mute_; |
| 636 | } |
| 637 | |
| 638 | int ChannelSend::SendTelephoneEventOutband(int event, int duration_ms) { |
| 639 | RTC_DCHECK_LE(0, event); |
| 640 | RTC_DCHECK_GE(255, event); |
| 641 | RTC_DCHECK_LE(0, duration_ms); |
| 642 | RTC_DCHECK_GE(65535, duration_ms); |
| 643 | if (!Sending()) { |
| 644 | return -1; |
| 645 | } |
| 646 | if (_rtpRtcpModule->SendTelephoneEventOutband( |
| 647 | event, duration_ms, kTelephoneEventAttenuationdB) != 0) { |
| 648 | RTC_DLOG(LS_ERROR) << "SendTelephoneEventOutband() failed to send event"; |
| 649 | return -1; |
| 650 | } |
| 651 | return 0; |
| 652 | } |
| 653 | |
| 654 | int ChannelSend::SetSendTelephoneEventPayloadType(int payload_type, |
| 655 | int payload_frequency) { |
| 656 | RTC_DCHECK_LE(0, payload_type); |
| 657 | RTC_DCHECK_GE(127, payload_type); |
| 658 | CodecInst codec = {0}; |
| 659 | codec.pltype = payload_type; |
| 660 | codec.plfreq = payload_frequency; |
| 661 | memcpy(codec.plname, "telephone-event", 16); |
| 662 | if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) { |
| 663 | _rtpRtcpModule->DeRegisterSendPayload(codec.pltype); |
| 664 | if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) { |
| 665 | RTC_DLOG(LS_ERROR) |
| 666 | << "SetSendTelephoneEventPayloadType() failed to register " |
| 667 | "send payload type"; |
| 668 | return -1; |
| 669 | } |
| 670 | } |
| 671 | return 0; |
| 672 | } |
| 673 | |
| 674 | int ChannelSend::SetLocalSSRC(unsigned int ssrc) { |
| 675 | if (channel_state_.Get().sending) { |
| 676 | RTC_DLOG(LS_ERROR) << "SetLocalSSRC() already sending"; |
| 677 | return -1; |
| 678 | } |
| 679 | _rtpRtcpModule->SetSSRC(ssrc); |
| 680 | return 0; |
| 681 | } |
| 682 | |
| 683 | void ChannelSend::SetMid(const std::string& mid, int extension_id) { |
| 684 | int ret = SetSendRtpHeaderExtension(true, kRtpExtensionMid, extension_id); |
| 685 | RTC_DCHECK_EQ(0, ret); |
| 686 | _rtpRtcpModule->SetMid(mid); |
| 687 | } |
| 688 | |
| 689 | int ChannelSend::SetSendAudioLevelIndicationStatus(bool enable, |
| 690 | unsigned char id) { |
| 691 | _includeAudioLevelIndication = enable; |
| 692 | return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id); |
| 693 | } |
| 694 | |
| 695 | void ChannelSend::EnableSendTransportSequenceNumber(int id) { |
| 696 | int ret = |
| 697 | SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id); |
| 698 | RTC_DCHECK_EQ(0, ret); |
| 699 | } |
| 700 | |
| 701 | void ChannelSend::RegisterSenderCongestionControlObjects( |
| 702 | RtpTransportControllerSendInterface* transport, |
| 703 | RtcpBandwidthObserver* bandwidth_observer) { |
| 704 | RtpPacketSender* rtp_packet_sender = transport->packet_sender(); |
| 705 | TransportFeedbackObserver* transport_feedback_observer = |
| 706 | transport->transport_feedback_observer(); |
| 707 | PacketRouter* packet_router = transport->packet_router(); |
| 708 | |
| 709 | RTC_DCHECK(rtp_packet_sender); |
| 710 | RTC_DCHECK(transport_feedback_observer); |
| 711 | RTC_DCHECK(packet_router); |
| 712 | RTC_DCHECK(!packet_router_); |
| 713 | rtcp_observer_->SetBandwidthObserver(bandwidth_observer); |
| 714 | feedback_observer_proxy_->SetTransportFeedbackObserver( |
| 715 | transport_feedback_observer); |
| 716 | seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router); |
| 717 | rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender); |
| 718 | _rtpRtcpModule->SetStorePacketsStatus(true, 600); |
| 719 | constexpr bool remb_candidate = false; |
| 720 | packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate); |
| 721 | packet_router_ = packet_router; |
| 722 | } |
| 723 | |
| 724 | void ChannelSend::ResetSenderCongestionControlObjects() { |
| 725 | RTC_DCHECK(packet_router_); |
| 726 | _rtpRtcpModule->SetStorePacketsStatus(false, 600); |
| 727 | rtcp_observer_->SetBandwidthObserver(nullptr); |
| 728 | feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr); |
| 729 | seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr); |
| 730 | packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get()); |
| 731 | packet_router_ = nullptr; |
| 732 | rtp_packet_sender_proxy_->SetPacketSender(nullptr); |
| 733 | } |
| 734 | |
| 735 | void ChannelSend::SetRTCPStatus(bool enable) { |
| 736 | _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff); |
| 737 | } |
| 738 | |
| 739 | int ChannelSend::SetRTCP_CNAME(const char cName[256]) { |
| 740 | if (_rtpRtcpModule->SetCNAME(cName) != 0) { |
| 741 | RTC_DLOG(LS_ERROR) << "SetRTCP_CNAME() failed to set RTCP CNAME"; |
| 742 | return -1; |
| 743 | } |
| 744 | return 0; |
| 745 | } |
| 746 | |
| 747 | int ChannelSend::GetRemoteRTCPReportBlocks( |
| 748 | std::vector<ReportBlock>* report_blocks) { |
| 749 | if (report_blocks == NULL) { |
| 750 | RTC_DLOG(LS_ERROR) << "GetRemoteRTCPReportBlock()s invalid report_blocks."; |
| 751 | return -1; |
| 752 | } |
| 753 | |
| 754 | // Get the report blocks from the latest received RTCP Sender or Receiver |
| 755 | // Report. Each element in the vector contains the sender's SSRC and a |
| 756 | // report block according to RFC 3550. |
| 757 | std::vector<RTCPReportBlock> rtcp_report_blocks; |
| 758 | if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) { |
| 759 | return -1; |
| 760 | } |
| 761 | |
| 762 | if (rtcp_report_blocks.empty()) |
| 763 | return 0; |
| 764 | |
| 765 | std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin(); |
| 766 | for (; it != rtcp_report_blocks.end(); ++it) { |
| 767 | ReportBlock report_block; |
| 768 | report_block.sender_SSRC = it->sender_ssrc; |
| 769 | report_block.source_SSRC = it->source_ssrc; |
| 770 | report_block.fraction_lost = it->fraction_lost; |
| 771 | report_block.cumulative_num_packets_lost = it->packets_lost; |
| 772 | report_block.extended_highest_sequence_number = |
| 773 | it->extended_highest_sequence_number; |
| 774 | report_block.interarrival_jitter = it->jitter; |
| 775 | report_block.last_SR_timestamp = it->last_sender_report_timestamp; |
| 776 | report_block.delay_since_last_SR = it->delay_since_last_sender_report; |
| 777 | report_blocks->push_back(report_block); |
| 778 | } |
| 779 | return 0; |
| 780 | } |
| 781 | |
| 782 | int ChannelSend::GetRTPStatistics(CallSendStatistics& stats) { |
| 783 | // --- RtcpStatistics |
| 784 | |
| 785 | // --- RTT |
| 786 | stats.rttMs = GetRTT(); |
| 787 | |
| 788 | // --- Data counters |
| 789 | |
| 790 | size_t bytesSent(0); |
| 791 | uint32_t packetsSent(0); |
| 792 | |
| 793 | if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) { |
| 794 | RTC_DLOG(LS_WARNING) |
| 795 | << "GetRTPStatistics() failed to retrieve RTP datacounters" |
| 796 | << " => output will not be complete"; |
| 797 | } |
| 798 | |
| 799 | stats.bytesSent = bytesSent; |
| 800 | stats.packetsSent = packetsSent; |
| 801 | |
| 802 | return 0; |
| 803 | } |
| 804 | |
| 805 | void ChannelSend::SetNACKStatus(bool enable, int maxNumberOfPackets) { |
| 806 | // None of these functions can fail. |
| 807 | if (enable) |
| 808 | audio_coding_->EnableNack(maxNumberOfPackets); |
| 809 | else |
| 810 | audio_coding_->DisableNack(); |
| 811 | } |
| 812 | |
| 813 | // Called when we are missing one or more packets. |
| 814 | int ChannelSend::ResendPackets(const uint16_t* sequence_numbers, int length) { |
| 815 | return _rtpRtcpModule->SendNACK(sequence_numbers, length); |
| 816 | } |
| 817 | |
| 818 | void ChannelSend::ProcessAndEncodeAudio( |
| 819 | std::unique_ptr<AudioFrame> audio_frame) { |
| 820 | // Avoid posting any new tasks if sending was already stopped in StopSend(). |
| 821 | rtc::CritScope cs(&encoder_queue_lock_); |
| 822 | if (!encoder_queue_is_active_) { |
| 823 | return; |
| 824 | } |
| 825 | // Profile time between when the audio frame is added to the task queue and |
| 826 | // when the task is actually executed. |
| 827 | audio_frame->UpdateProfileTimeStamp(); |
| 828 | encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>( |
| 829 | new ProcessAndEncodeAudioTask(std::move(audio_frame), this))); |
| 830 | } |
| 831 | |
| 832 | void ChannelSend::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) { |
| 833 | RTC_DCHECK_RUN_ON(encoder_queue_); |
| 834 | RTC_DCHECK_GT(audio_input->samples_per_channel_, 0); |
| 835 | RTC_DCHECK_LE(audio_input->num_channels_, 2); |
| 836 | |
| 837 | // Measure time between when the audio frame is added to the task queue and |
| 838 | // when the task is actually executed. Goal is to keep track of unwanted |
| 839 | // extra latency added by the task queue. |
| 840 | RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs", |
| 841 | audio_input->ElapsedProfileTimeMs()); |
| 842 | |
| 843 | bool is_muted = InputMute(); |
| 844 | AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted); |
| 845 | |
| 846 | if (_includeAudioLevelIndication) { |
| 847 | size_t length = |
| 848 | audio_input->samples_per_channel_ * audio_input->num_channels_; |
| 849 | RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes); |
| 850 | if (is_muted && previous_frame_muted_) { |
| 851 | rms_level_.AnalyzeMuted(length); |
| 852 | } else { |
| 853 | rms_level_.Analyze( |
| 854 | rtc::ArrayView<const int16_t>(audio_input->data(), length)); |
| 855 | } |
| 856 | } |
| 857 | previous_frame_muted_ = is_muted; |
| 858 | |
| 859 | // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz. |
| 860 | |
| 861 | // The ACM resamples internally. |
| 862 | audio_input->timestamp_ = _timeStamp; |
| 863 | // This call will trigger AudioPacketizationCallback::SendData if encoding |
| 864 | // is done and payload is ready for packetization and transmission. |
| 865 | // Otherwise, it will return without invoking the callback. |
| 866 | if (audio_coding_->Add10MsData(*audio_input) < 0) { |
| 867 | RTC_DLOG(LS_ERROR) << "ACM::Add10MsData() failed."; |
| 868 | return; |
| 869 | } |
| 870 | |
| 871 | _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_); |
| 872 | } |
| 873 | |
| 874 | void ChannelSend::UpdateOverheadForEncoder() { |
| 875 | size_t overhead_per_packet = |
| 876 | transport_overhead_per_packet_ + rtp_overhead_per_packet_; |
| 877 | audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { |
| 878 | if (*encoder) { |
| 879 | (*encoder)->OnReceivedOverhead(overhead_per_packet); |
| 880 | } |
| 881 | }); |
| 882 | } |
| 883 | |
| 884 | void ChannelSend::SetTransportOverhead(size_t transport_overhead_per_packet) { |
| 885 | rtc::CritScope cs(&overhead_per_packet_lock_); |
| 886 | transport_overhead_per_packet_ = transport_overhead_per_packet; |
| 887 | UpdateOverheadForEncoder(); |
| 888 | } |
| 889 | |
| 890 | // TODO(solenberg): Make AudioSendStream an OverheadObserver instead. |
| 891 | void ChannelSend::OnOverheadChanged(size_t overhead_bytes_per_packet) { |
| 892 | rtc::CritScope cs(&overhead_per_packet_lock_); |
| 893 | rtp_overhead_per_packet_ = overhead_bytes_per_packet; |
| 894 | UpdateOverheadForEncoder(); |
| 895 | } |
| 896 | |
| 897 | ANAStats ChannelSend::GetANAStatistics() const { |
| 898 | return audio_coding_->GetANAStats(); |
| 899 | } |
| 900 | |
| 901 | RtpRtcp* ChannelSend::GetRtpRtcp() const { |
| 902 | return _rtpRtcpModule.get(); |
| 903 | } |
| 904 | |
| 905 | int ChannelSend::SetSendRtpHeaderExtension(bool enable, |
| 906 | RTPExtensionType type, |
| 907 | unsigned char id) { |
| 908 | int error = 0; |
| 909 | _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type); |
| 910 | if (enable) { |
| 911 | error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id); |
| 912 | } |
| 913 | return error; |
| 914 | } |
| 915 | |
| 916 | int ChannelSend::GetRtpTimestampRateHz() const { |
| 917 | const auto format = audio_coding_->ReceiveFormat(); |
| 918 | // Default to the playout frequency if we've not gotten any packets yet. |
| 919 | // TODO(ossu): Zero clockrate can only happen if we've added an external |
| 920 | // decoder for a format we don't support internally. Remove once that way of |
| 921 | // adding decoders is gone! |
| 922 | return (format && format->clockrate_hz != 0) |
| 923 | ? format->clockrate_hz |
| 924 | : audio_coding_->PlayoutFrequency(); |
| 925 | } |
| 926 | |
| 927 | int64_t ChannelSend::GetRTT() const { |
| 928 | RtcpMode method = _rtpRtcpModule->RTCP(); |
| 929 | if (method == RtcpMode::kOff) { |
| 930 | return 0; |
| 931 | } |
| 932 | std::vector<RTCPReportBlock> report_blocks; |
| 933 | _rtpRtcpModule->RemoteRTCPStat(&report_blocks); |
| 934 | |
| 935 | if (report_blocks.empty()) { |
| 936 | return 0; |
| 937 | } |
| 938 | |
| 939 | int64_t rtt = 0; |
| 940 | int64_t avg_rtt = 0; |
| 941 | int64_t max_rtt = 0; |
| 942 | int64_t min_rtt = 0; |
| 943 | // We don't know in advance the remote ssrc used by the other end's receiver |
| 944 | // reports, so use the SSRC of the first report block for calculating the RTT. |
| 945 | if (_rtpRtcpModule->RTT(report_blocks[0].sender_ssrc, &rtt, &avg_rtt, |
| 946 | &min_rtt, &max_rtt) != 0) { |
| 947 | return 0; |
| 948 | } |
| 949 | return rtt; |
| 950 | } |
| 951 | |
| 952 | } // namespace voe |
| 953 | } // namespace webrtc |