| 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_receive.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <map> |
| 15 | #include <memory> |
| 16 | #include <string> |
| 17 | #include <utility> |
| 18 | #include <vector> |
| 19 |
| 20 | #include "api/crypto/frame_decryptor_interface.h" |
| 21 | #include "api/frame_transformer_interface.h" |
| 22 | #include "api/rtc_event_log/rtc_event_log.h" |
| 23 | #include "api/sequence_checker.h" |
| 24 | #include "api/task_queue/pending_task_safety_flag.h" |
| 25 | #include "api/task_queue/task_queue_base.h" |
| 26 | #include "api/units/time_delta.h" |
| 27 | #include "audio/audio_level.h" |
| 28 | #include "audio/channel_receive_frame_transformer_delegate.h" |
| 29 | #include "audio/channel_send.h" |
| 30 | #include "audio/utility/audio_frame_operations.h" |
| 31 | #include "logging/rtc_event_log/events/rtc_event_audio_playout.h" |
| 32 | #include "logging/rtc_event_log/events/rtc_event_neteq_set_minimum_delay.h" |
| 33 | #include "modules/audio_coding/acm2/acm_receiver.h" |
| 34 | #include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h" |
| 35 | #include "modules/audio_device/include/audio_device.h" |
| 36 | #include "modules/pacing/packet_router.h" |
| 37 | #include "modules/rtp_rtcp/include/receive_statistics.h" |
| 38 | #include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h" |
| 39 | #include "modules/rtp_rtcp/source/absolute_capture_time_interpolator.h" |
| 40 | #include "modules/rtp_rtcp/source/capture_clock_offset_updater.h" |
| 41 | #include "modules/rtp_rtcp/source/rtp_header_extensions.h" |
| 42 | #include "modules/rtp_rtcp/source/rtp_packet_received.h" |
| 43 | #include "modules/rtp_rtcp/source/rtp_rtcp_config.h" |
| 44 | #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h" |
| 45 | #include "rtc_base/checks.h" |
| 46 | #include "rtc_base/logging.h" |
| 47 | #include "rtc_base/numerics/safe_minmax.h" |
| 48 | #include "rtc_base/numerics/sequence_number_unwrapper.h" |
| 49 | #include "rtc_base/race_checker.h" |
| 50 | #include "rtc_base/strings/string_builder.h" |
| 51 | #include "rtc_base/synchronization/mutex.h" |
| 52 | #include "rtc_base/system/no_unique_address.h" |
| 53 | #include "rtc_base/time_utils.h" |
| 54 | #include "rtc_base/trace_event.h" |
| 55 | #include "system_wrappers/include/metrics.h" |
| 56 | #include "system_wrappers/include/ntp_time.h" |
| 57 |
| 58 | namespace webrtc { |
| 59 | namespace voe { |
| 60 |
| 61 | namespace { |
| 62 |
| 63 | constexpr double kAudioSampleDurationSeconds = 0.01; |
| 64 |
| 65 | // Video Sync. |
| 66 | constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0; |
| 67 | constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000; |
| 68 |
| 69 | acm2::AcmReceiver::Config AcmConfig( |
| 70 | NetEqFactory* neteq_factory, |
| 71 | rtc::scoped_refptr<AudioDecoderFactory> decoder_factory, |
| 72 | absl::optional<AudioCodecPairId> codec_pair_id, |
| 73 | size_t jitter_buffer_max_packets, |
| 74 | bool jitter_buffer_fast_playout, |
| 75 | int jitter_buffer_min_delay_ms) { |
| 76 | acm2::AcmReceiver::Config acm_config; |
| 77 | acm_config.neteq_factory = neteq_factory; |
| 78 | acm_config.decoder_factory = decoder_factory; |
| 79 | acm_config.neteq_config.codec_pair_id = codec_pair_id; |
| 80 | acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets; |
| 81 | acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout; |
| 82 | acm_config.neteq_config.enable_muted_state = true; |
| 83 | acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms; |
| 84 |
| 85 | return acm_config; |
| 86 | } |
| 87 |
| 88 | class ChannelReceive : public ChannelReceiveInterface, |
| 89 | public RtcpPacketTypeCounterObserver { |
| 90 | public: |
| 91 | // Used for receive streams. |
| 92 | ChannelReceive( |
| 93 | Clock* clock, |
| 94 | NetEqFactory* neteq_factory, |
| 95 | AudioDeviceModule* audio_device_module, |
| 96 | Transport* rtcp_send_transport, |
| 97 | RtcEventLog* rtc_event_log, |
| 98 | uint32_t local_ssrc, |
| 99 | uint32_t remote_ssrc, |
| 100 | size_t jitter_buffer_max_packets, |
| 101 | bool jitter_buffer_fast_playout, |
| 102 | int jitter_buffer_min_delay_ms, |
| 103 | bool enable_non_sender_rtt, |
| 104 | rtc::scoped_refptr<AudioDecoderFactory> decoder_factory, |
| 105 | absl::optional<AudioCodecPairId> codec_pair_id, |
| 106 | rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor, |
| 107 | const webrtc::CryptoOptions& crypto_options, |
| 108 | rtc::scoped_refptr<FrameTransformerInterface> frame_transformer); |
| 109 | ~ChannelReceive() override; |
| 110 |
| 111 | void SetSink(AudioSinkInterface* sink) override; |
| 112 |
| 113 | void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override; |
| 114 |
| 115 | // API methods |
| 116 |
| 117 | void StartPlayout() override; |
| 118 | void StopPlayout() override; |
| 119 |
| 120 | // Codecs |
| 121 | absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec() |
| 122 | const override; |
| 123 |
| 124 | void ReceivedRTCPPacket(const uint8_t* data, size_t length) override; |
| 125 |
| 126 | // RtpPacketSinkInterface. |
| 127 | void OnRtpPacket(const RtpPacketReceived& packet) override; |
| 128 |
| 129 | // Muting, Volume and Level. |
| 130 | void SetChannelOutputVolumeScaling(float scaling) override; |
| 131 | int GetSpeechOutputLevelFullRange() const override; |
| 132 | // See description of "totalAudioEnergy" in the WebRTC stats spec: |
| 133 | // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy |
| 134 | double GetTotalOutputEnergy() const override; |
| 135 | double GetTotalOutputDuration() const override; |
| 136 |
| 137 | // Stats. |
| 138 | NetworkStatistics GetNetworkStatistics( |
| 139 | bool get_and_clear_legacy_stats) const override; |
| 140 | AudioDecodingCallStats GetDecodingCallStatistics() const override; |
| 141 |
| 142 | // Audio+Video Sync. |
| 143 | uint32_t GetDelayEstimate() const override; |
| 144 | bool SetMinimumPlayoutDelay(int delayMs) override; |
| 145 | bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp, |
| 146 | int64_t* time_ms) const override; |
| 147 | void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms, |
| 148 | int64_t time_ms) override; |
| 149 | absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs( |
| 150 | int64_t now_ms) const override; |
| 151 |
| 152 | // Audio quality. |
| 153 | bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override; |
| 154 | int GetBaseMinimumPlayoutDelayMs() const override; |
| 155 |
| 156 | // Produces the transport-related timestamps; current_delay_ms is left unset. |
| 157 | absl::optional<Syncable::Info> GetSyncInfo() const override; |
| 158 |
| 159 | void RegisterReceiverCongestionControlObjects( |
| 160 | PacketRouter* packet_router) override; |
| 161 | void ResetReceiverCongestionControlObjects() override; |
| 162 |
| 163 | CallReceiveStatistics GetRTCPStatistics() const override; |
| 164 | void SetNACKStatus(bool enable, int maxNumberOfPackets) override; |
| 165 | void SetNonSenderRttMeasurement(bool enabled) override; |
| 166 |
| 167 | AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo( |
| 168 | int sample_rate_hz, |
| 169 | AudioFrame* audio_frame) override; |
| 170 |
| 171 | int PreferredSampleRate() const override; |
| 172 |
| 173 | void SetSourceTracker(SourceTracker* source_tracker) override; |
| 174 |
| 175 | // Associate to a send channel. |
| 176 | // Used for obtaining RTT for a receive-only channel. |
| 177 | void SetAssociatedSendChannel(const ChannelSendInterface* channel) override; |
| 178 |
| 179 | // Sets a frame transformer between the depacketizer and the decoder, to |
| 180 | // transform the received frames before decoding them. |
| 181 | void SetDepacketizerToDecoderFrameTransformer( |
| 182 | rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) |
| 183 | override; |
| 184 |
| 185 | void SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface> |
| 186 | frame_decryptor) override; |
| 187 |
| 188 | void OnLocalSsrcChange(uint32_t local_ssrc) override; |
| 189 | uint32_t GetLocalSsrc() const override; |
| 190 |
| 191 | void RtcpPacketTypesCounterUpdated( |
| 192 | uint32_t ssrc, |
| 193 | const RtcpPacketTypeCounter& packet_counter) override; |
| 194 |
| 195 | private: |
| 196 | void ReceivePacket(const uint8_t* packet, |
| 197 | size_t packet_length, |
| 198 | const RTPHeader& header) |
| 199 | RTC_RUN_ON(worker_thread_checker_); |
| 200 | int ResendPackets(const uint16_t* sequence_numbers, int length); |
| 201 | void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) |
| 202 | RTC_RUN_ON(worker_thread_checker_); |
| 203 |
| 204 | int GetRtpTimestampRateHz() const; |
| 205 |
| 206 | void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload, |
| 207 | const RTPHeader& rtpHeader) |
| 208 | RTC_RUN_ON(worker_thread_checker_); |
| 209 |
| 210 | void InitFrameTransformerDelegate( |
| 211 | rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) |
| 212 | RTC_RUN_ON(worker_thread_checker_); |
| 213 |
| 214 | // Thread checkers document and lock usage of some methods to specific threads |
| 215 | // we know about. The goal is to eventually split up voe::ChannelReceive into |
| 216 | // parts with single-threaded semantics, and thereby reduce the need for |
| 217 | // locks. |
| 218 | RTC_NO_UNIQUE_ADDRESS SequenceChecker worker_thread_checker_; |
| 219 | RTC_NO_UNIQUE_ADDRESS SequenceChecker network_thread_checker_; |
| 220 |
| 221 | TaskQueueBase* const worker_thread_; |
| 222 | ScopedTaskSafety worker_safety_; |
| 223 |
| 224 | // Methods accessed from audio and video threads are checked for sequential- |
| 225 | // only access. We don't necessarily own and control these threads, so thread |
| 226 | // checkers cannot be used. E.g. Chromium may transfer "ownership" from one |
| 227 | // audio thread to another, but access is still sequential. |
| 228 | rtc::RaceChecker audio_thread_race_checker_; |
| 229 | Mutex callback_mutex_; |
| 230 | Mutex volume_settings_mutex_; |
| 231 |
| 232 | bool playing_ RTC_GUARDED_BY(worker_thread_checker_) = false; |
| 233 |
| 234 | RtcEventLog* const event_log_; |
| 235 |
| 236 | // Indexed by payload type. |
| 237 | std::map<uint8_t, int> payload_type_frequencies_; |
| 238 |
| 239 | std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_; |
| 240 | std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_; |
| 241 | const uint32_t remote_ssrc_; |
| 242 | SourceTracker* source_tracker_ = nullptr; |
| 243 |
| 244 | // Info for GetSyncInfo is updated on network or worker thread, and queried on |
| 245 | // the worker thread. |
| 246 | absl::optional<uint32_t> last_received_rtp_timestamp_ |
| 247 | RTC_GUARDED_BY(&worker_thread_checker_); |
| 248 | absl::optional<int64_t> last_received_rtp_system_time_ms_ |
| 249 | RTC_GUARDED_BY(&worker_thread_checker_); |
| 250 |
| 251 | // The AcmReceiver is thread safe, using its own lock. |
| 252 | acm2::AcmReceiver acm_receiver_; |
| 253 | AudioSinkInterface* audio_sink_ = nullptr; |
| 254 | AudioLevel _outputAudioLevel; |
| 255 |
| 256 | Clock* const clock_; |
| 257 | RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_); |
| 258 |
| 259 | // Timestamp of the audio pulled from NetEq. |
| 260 | absl::optional<uint32_t> jitter_buffer_playout_timestamp_; |
| 261 |
| 262 | uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(worker_thread_checker_); |
| 263 | absl::optional<int64_t> playout_timestamp_rtp_time_ms_ |
| 264 | RTC_GUARDED_BY(worker_thread_checker_); |
| 265 | uint32_t playout_delay_ms_ RTC_GUARDED_BY(worker_thread_checker_); |
| 266 | absl::optional<int64_t> playout_timestamp_ntp_ |
| 267 | RTC_GUARDED_BY(worker_thread_checker_); |
| 268 | absl::optional<int64_t> playout_timestamp_ntp_time_ms_ |
| 269 | RTC_GUARDED_BY(worker_thread_checker_); |
| 270 |
| 271 | mutable Mutex ts_stats_lock_; |
| 272 |
| 273 | webrtc::RtpTimestampUnwrapper rtp_ts_wraparound_handler_; |
| 274 | // The rtp timestamp of the first played out audio frame. |
| 275 | int64_t capture_start_rtp_time_stamp_; |
| 276 | // The capture ntp time (in local timebase) of the first played out audio |
| 277 | // frame. |
| 278 | int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_); |
| 279 |
| 280 | AudioDeviceModule* _audioDeviceModulePtr; |
| 281 | float _outputGain RTC_GUARDED_BY(volume_settings_mutex_); |
| 282 |
| 283 | const ChannelSendInterface* associated_send_channel_ |
| 284 | RTC_GUARDED_BY(network_thread_checker_); |
| 285 |
| 286 | PacketRouter* packet_router_ = nullptr; |
| 287 |
| 288 | SequenceChecker construction_thread_; |
| 289 |
| 290 | // E2EE Audio Frame Decryption |
| 291 | rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_ |
| 292 | RTC_GUARDED_BY(worker_thread_checker_); |
| 293 | webrtc::CryptoOptions crypto_options_; |
| 294 |
| 295 | webrtc::AbsoluteCaptureTimeInterpolator absolute_capture_time_interpolator_ |
| 296 | RTC_GUARDED_BY(worker_thread_checker_); |
| 297 |
| 298 | webrtc::CaptureClockOffsetUpdater capture_clock_offset_updater_ |
| 299 | RTC_GUARDED_BY(ts_stats_lock_); |
| 300 |
| 301 | rtc::scoped_refptr<ChannelReceiveFrameTransformerDelegate> |
| 302 | frame_transformer_delegate_; |
| 303 |
| 304 | // Counter that's used to control the frequency of reporting histograms |
| 305 | // from the `GetAudioFrameWithInfo` callback. |
| 306 | int audio_frame_interval_count_ RTC_GUARDED_BY(audio_thread_race_checker_) = |
| 307 | 0; |
| 308 | // Controls how many callbacks we let pass by before reporting callback stats. |
| 309 | // A value of 100 means 100 callbacks, each one of which represents 10ms worth |
| 310 | // of data, so the stats reporting frequency will be 1Hz (modulo failures). |
| 311 | constexpr static int kHistogramReportingInterval = 100; |
| 312 |
| 313 | mutable Mutex rtcp_counter_mutex_; |
| 314 | RtcpPacketTypeCounter rtcp_packet_type_counter_ |
| 315 | RTC_GUARDED_BY(rtcp_counter_mutex_); |
| 316 |
| 317 | std::map<int, SdpAudioFormat> payload_type_map_; |
| 318 | }; |
| 319 |
| 320 | void ChannelReceive::OnReceivedPayloadData( |
| 321 | rtc::ArrayView<const uint8_t> payload, |
| 322 | const RTPHeader& rtpHeader) { |
| 323 | if (!playing_) { |
| 324 | // Avoid inserting into NetEQ when we are not playing. Count the |
| 325 | // packet as discarded. |
| 326 |
| 327 | // If we have a source_tracker_, tell it that the frame has been |
| 328 | // "delivered". Normally, this happens in AudioReceiveStreamInterface when |
| 329 | // audio frames are pulled out, but when playout is muted, nothing is |
| 330 | // pulling frames. The downside of this approach is that frames delivered |
| 331 | // this way won't be delayed for playout, and therefore will be |
| 332 | // unsynchronized with (a) audio delay when playing and (b) any audio/video |
| 333 | // synchronization. But the alternative is that muting playout also stops |
| 334 | // the SourceTracker from updating RtpSource information. |
| 335 | if (source_tracker_) { |
| 336 | RtpPacketInfos::vector_type packet_vector = { |
| 337 | RtpPacketInfo(rtpHeader, clock_->CurrentTime())}; |
| 338 | source_tracker_->OnFrameDelivered(RtpPacketInfos(packet_vector)); |
| 339 | } |
| 340 |
| 341 | return; |
| 342 | } |
| 343 |
| 344 | // Push the incoming payload (parsed and ready for decoding) into the ACM |
| 345 | if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) { |
| 346 | RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to " |
| 347 | "push data to the ACM"; |
| 348 | return; |
| 349 | } |
| 350 |
| 351 | TimeDelta round_trip_time = rtp_rtcp_->LastRtt().value_or(TimeDelta::Zero()); |
| 352 |
| 353 | std::vector<uint16_t> nack_list = |
| 354 | acm_receiver_.GetNackList(round_trip_time.ms()); |
| 355 | if (!nack_list.empty()) { |
| 356 | // Can't use nack_list.data() since it's not supported by all |
| 357 | // compilers. |
| 358 | ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size())); |
| 359 | } |
| 360 | } |
| 361 |
| 362 | void ChannelReceive::InitFrameTransformerDelegate( |
| 363 | rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) { |
| 364 | RTC_DCHECK(frame_transformer); |
| 365 | RTC_DCHECK(!frame_transformer_delegate_); |
| 366 | RTC_DCHECK(worker_thread_->IsCurrent()); |
| 367 |
| 368 | // Pass a callback to ChannelReceive::OnReceivedPayloadData, to be called by |
| 369 | // the delegate to receive transformed audio. |
| 370 | ChannelReceiveFrameTransformerDelegate::ReceiveFrameCallback |
| 371 | receive_audio_callback = [this](rtc::ArrayView<const uint8_t> packet, |
| 372 | const RTPHeader& header) { |
| 373 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 374 | OnReceivedPayloadData(packet, header); |
| 375 | }; |
| 376 | frame_transformer_delegate_ = |
| 377 | rtc::make_ref_counted<ChannelReceiveFrameTransformerDelegate>( |
| 378 | std::move(receive_audio_callback), std::move(frame_transformer), |
| 379 | worker_thread_); |
| 380 | frame_transformer_delegate_->Init(); |
| 381 | } |
| 382 |
| 383 | AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo( |
| 384 | int sample_rate_hz, |
| 385 | AudioFrame* audio_frame) { |
| 386 | TRACE_EVENT_BEGIN1("webrtc", "ChannelReceive::GetAudioFrameWithInfo", |
| 387 | "sample_rate_hz", sample_rate_hz); |
| 388 | RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); |
| 389 | audio_frame->sample_rate_hz_ = sample_rate_hz; |
| 390 |
| 391 | event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_)); |
| 392 |
| 393 | // Get 10ms raw PCM data from the ACM (mixer limits output frequency) |
| 394 | bool muted; |
| 395 | if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame, |
| 396 | &muted) == -1) { |
| 397 | RTC_DLOG(LS_ERROR) |
| 398 | << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!"; |
| 399 | // In all likelihood, the audio in this frame is garbage. We return an |
| 400 | // error so that the audio mixer module doesn't add it to the mix. As |
| 401 | // a result, it won't be played out and the actions skipped here are |
| 402 | // irrelevant. |
| 403 |
| 404 | TRACE_EVENT_END1("webrtc", "ChannelReceive::GetAudioFrameWithInfo", "error", |
| 405 | 1); |
| 406 | return AudioMixer::Source::AudioFrameInfo::kError; |
| 407 | } |
| 408 |
| 409 | if (muted) { |
| 410 | // TODO(henrik.lundin): We should be able to do better than this. But we |
| 411 | // will have to go through all the cases below where the audio samples may |
| 412 | // be used, and handle the muted case in some way. |
| 413 | AudioFrameOperations::Mute(audio_frame); |
| 414 | } |
| 415 |
| 416 | { |
| 417 | // Pass the audio buffers to an optional sink callback, before applying |
| 418 | // scaling/panning, as that applies to the mix operation. |
| 419 | // External recipients of the audio (e.g. via AudioTrack), will do their |
| 420 | // own mixing/dynamic processing. |
| 421 | MutexLock lock(&callback_mutex_); |
| 422 | if (audio_sink_) { |
| 423 | AudioSinkInterface::Data data( |
| 424 | audio_frame->data(), audio_frame->samples_per_channel_, |
| 425 | audio_frame->sample_rate_hz_, audio_frame->num_channels_, |
| 426 | audio_frame->timestamp_); |
| 427 | audio_sink_->OnData(data); |
| 428 | } |
| 429 | } |
| 430 |
| 431 | float output_gain = 1.0f; |
| 432 | { |
| 433 | MutexLock lock(&volume_settings_mutex_); |
| 434 | output_gain = _outputGain; |
| 435 | } |
| 436 |
| 437 | // Output volume scaling |
| 438 | if (output_gain < 0.99f || output_gain > 1.01f) { |
| 439 | // TODO(solenberg): Combine with mute state - this can cause clicks! |
| 440 | AudioFrameOperations::ScaleWithSat(output_gain, audio_frame); |
| 441 | } |
| 442 |
| 443 | // Measure audio level (0-9) |
| 444 | // TODO(henrik.lundin) Use the `muted` information here too. |
| 445 | // TODO(deadbeef): Use RmsLevel for `_outputAudioLevel` (see |
| 446 | // https://crbug.com/webrtc/7517). |
| 447 | _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds); |
| 448 |
| 449 | if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) { |
| 450 | // The first frame with a valid rtp timestamp. |
| 451 | capture_start_rtp_time_stamp_ = audio_frame->timestamp_; |
| 452 | } |
| 453 |
| 454 | if (capture_start_rtp_time_stamp_ >= 0) { |
| 455 | // audio_frame.timestamp_ should be valid from now on. |
| 456 | // Compute elapsed time. |
| 457 | int64_t unwrap_timestamp = |
| 458 | rtp_ts_wraparound_handler_.Unwrap(audio_frame->timestamp_); |
| 459 | audio_frame->elapsed_time_ms_ = |
| 460 | (unwrap_timestamp - capture_start_rtp_time_stamp_) / |
| 461 | (GetRtpTimestampRateHz() / 1000); |
| 462 |
| 463 | { |
| 464 | MutexLock lock(&ts_stats_lock_); |
| 465 | // Compute ntp time. |
| 466 | audio_frame->ntp_time_ms_ = |
| 467 | ntp_estimator_.Estimate(audio_frame->timestamp_); |
| 468 | // `ntp_time_ms_` won't be valid until at least 2 RTCP SRs are received. |
| 469 | if (audio_frame->ntp_time_ms_ > 0) { |
| 470 | // Compute `capture_start_ntp_time_ms_` so that |
| 471 | // `capture_start_ntp_time_ms_` + `elapsed_time_ms_` == `ntp_time_ms_` |
| 472 | capture_start_ntp_time_ms_ = |
| 473 | audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_; |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 |
| 478 | // Fill in local capture clock offset in `audio_frame->packet_infos_`. |
| 479 | RtpPacketInfos::vector_type packet_infos; |
| 480 | for (auto& packet_info : audio_frame->packet_infos_) { |
| 481 | RtpPacketInfo new_packet_info(packet_info); |
| 482 | if (packet_info.absolute_capture_time().has_value()) { |
| 483 | MutexLock lock(&ts_stats_lock_); |
| 484 | new_packet_info.set_local_capture_clock_offset( |
| 485 | capture_clock_offset_updater_.ConvertsToTimeDela( |
| 486 | capture_clock_offset_updater_.AdjustEstimatedCaptureClockOffset( |
| 487 | packet_info.absolute_capture_time() |
| 488 | ->estimated_capture_clock_offset))); |
| 489 | } |
| 490 | packet_infos.push_back(std::move(new_packet_info)); |
| 491 | } |
| 492 | audio_frame->packet_infos_ = RtpPacketInfos(packet_infos); |
| 493 |
| 494 | ++audio_frame_interval_count_; |
| 495 | if (audio_frame_interval_count_ >= kHistogramReportingInterval) { |
| 496 | audio_frame_interval_count_ = 0; |
| 497 | worker_thread_->PostTask(SafeTask(worker_safety_.flag(), [this]() { |
| 498 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 499 | RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs", |
| 500 | acm_receiver_.TargetDelayMs()); |
| 501 | const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs(); |
| 502 | RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs", |
| 503 | jitter_buffer_delay + playout_delay_ms_); |
| 504 | RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs", |
| 505 | jitter_buffer_delay); |
| 506 | RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs", |
| 507 | playout_delay_ms_); |
| 508 | })); |
| 509 | } |
| 510 |
| 511 | TRACE_EVENT_END2("webrtc", "ChannelReceive::GetAudioFrameWithInfo", "gain", |
| 512 | output_gain, "muted", muted); |
| 513 | return muted ? AudioMixer::Source::AudioFrameInfo::kMuted |
| 514 | : AudioMixer::Source::AudioFrameInfo::kNormal; |
| 515 | } |
| 516 |
| 517 | int ChannelReceive::PreferredSampleRate() const { |
| 518 | RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); |
| 519 | // Return the bigger of playout and receive frequency in the ACM. |
| 520 | return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0), |
| 521 | acm_receiver_.last_output_sample_rate_hz()); |
| 522 | } |
| 523 |
| 524 | void ChannelReceive::SetSourceTracker(SourceTracker* source_tracker) { |
| 525 | source_tracker_ = source_tracker; |
| 526 | } |
| 527 |
| 528 | ChannelReceive::ChannelReceive( |
| 529 | Clock* clock, |
| 530 | NetEqFactory* neteq_factory, |
| 531 | AudioDeviceModule* audio_device_module, |
| 532 | Transport* rtcp_send_transport, |
| 533 | RtcEventLog* rtc_event_log, |
| 534 | uint32_t local_ssrc, |
| 535 | uint32_t remote_ssrc, |
| 536 | size_t jitter_buffer_max_packets, |
| 537 | bool jitter_buffer_fast_playout, |
| 538 | int jitter_buffer_min_delay_ms, |
| 539 | bool enable_non_sender_rtt, |
| 540 | rtc::scoped_refptr<AudioDecoderFactory> decoder_factory, |
| 541 | absl::optional<AudioCodecPairId> codec_pair_id, |
| 542 | rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor, |
| 543 | const webrtc::CryptoOptions& crypto_options, |
| 544 | rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) |
| 545 | : worker_thread_(TaskQueueBase::Current()), |
| 546 | event_log_(rtc_event_log), |
| 547 | rtp_receive_statistics_(ReceiveStatistics::Create(clock)), |
| 548 | remote_ssrc_(remote_ssrc), |
| 549 | acm_receiver_(AcmConfig(neteq_factory, |
| 550 | decoder_factory, |
| 551 | codec_pair_id, |
| 552 | jitter_buffer_max_packets, |
| 553 | jitter_buffer_fast_playout, |
| 554 | jitter_buffer_min_delay_ms)), |
| 555 | _outputAudioLevel(), |
| 556 | clock_(clock), |
| 557 | ntp_estimator_(clock), |
| 558 | playout_timestamp_rtp_(0), |
| 559 | playout_delay_ms_(0), |
| 560 | capture_start_rtp_time_stamp_(-1), |
| 561 | capture_start_ntp_time_ms_(-1), |
| 562 | _audioDeviceModulePtr(audio_device_module), |
| 563 | _outputGain(1.0f), |
| 564 | associated_send_channel_(nullptr), |
| 565 | frame_decryptor_(frame_decryptor), |
| 566 | crypto_options_(crypto_options), |
| 567 | absolute_capture_time_interpolator_(clock) { |
| 568 | RTC_DCHECK(audio_device_module); |
| 569 |
| 570 | network_thread_checker_.Detach(); |
| 571 |
| 572 | rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true); |
| 573 | RtpRtcpInterface::Configuration configuration; |
| 574 | configuration.clock = clock; |
| 575 | configuration.audio = true; |
| 576 | configuration.receiver_only = true; |
| 577 | configuration.outgoing_transport = rtcp_send_transport; |
| 578 | configuration.receive_statistics = rtp_receive_statistics_.get(); |
| 579 | configuration.event_log = event_log_; |
| 580 | configuration.local_media_ssrc = local_ssrc; |
| 581 | configuration.rtcp_packet_type_counter_observer = this; |
| 582 | configuration.non_sender_rtt_measurement = enable_non_sender_rtt; |
| 583 |
| 584 | if (frame_transformer) |
| 585 | InitFrameTransformerDelegate(std::move(frame_transformer)); |
| 586 |
| 587 | rtp_rtcp_ = ModuleRtpRtcpImpl2::Create(configuration); |
| 588 | rtp_rtcp_->SetRemoteSSRC(remote_ssrc_); |
| 589 |
| 590 | // Ensure that RTCP is enabled for the created channel. |
| 591 | rtp_rtcp_->SetRTCPStatus(RtcpMode::kCompound); |
| 592 | } |
| 593 |
| 594 | ChannelReceive::~ChannelReceive() { |
| 595 | RTC_DCHECK_RUN_ON(&construction_thread_); |
| 596 |
| 597 | // Resets the delegate's callback to ChannelReceive::OnReceivedPayloadData. |
| 598 | if (frame_transformer_delegate_) |
| 599 | frame_transformer_delegate_->Reset(); |
| 600 |
| 601 | StopPlayout(); |
| 602 | } |
| 603 |
| 604 | void ChannelReceive::SetSink(AudioSinkInterface* sink) { |
| 605 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 606 | MutexLock lock(&callback_mutex_); |
| 607 | audio_sink_ = sink; |
| 608 | } |
| 609 |
| 610 | void ChannelReceive::StartPlayout() { |
| 611 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 612 | playing_ = true; |
| 613 | } |
| 614 |
| 615 | void ChannelReceive::StopPlayout() { |
| 616 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 617 | playing_ = false; |
| 618 | _outputAudioLevel.ResetLevelFullRange(); |
| 619 | acm_receiver_.FlushBuffers(); |
| 620 | } |
| 621 |
| 622 | absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec() |
| 623 | const { |
| 624 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 625 | return acm_receiver_.LastDecoder(); |
| 626 | } |
| 627 |
| 628 | void ChannelReceive::SetReceiveCodecs( |
| 629 | const std::map<int, SdpAudioFormat>& codecs) { |
| 630 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 631 | for (const auto& kv : codecs) { |
| 632 | RTC_DCHECK_GE(kv.second.clockrate_hz, 1000); |
| 633 | payload_type_frequencies_[kv.first] = kv.second.clockrate_hz; |
| 634 | } |
| 635 | payload_type_map_ = codecs; |
| 636 | acm_receiver_.SetCodecs(codecs); |
| 637 | } |
| 638 |
| 639 | void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) { |
| 640 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 641 | // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the |
| 642 | // network thread. Once that's done, the same applies to |
| 643 | // UpdatePlayoutTimestamp and |
| 644 | int64_t now_ms = rtc::TimeMillis(); |
| 645 |
| 646 | last_received_rtp_timestamp_ = packet.Timestamp(); |
| 647 | last_received_rtp_system_time_ms_ = now_ms; |
| 648 |
| 649 | // Store playout timestamp for the received RTP packet |
| 650 | UpdatePlayoutTimestamp(false, now_ms); |
| 651 |
| 652 | const auto& it = payload_type_frequencies_.find(packet.PayloadType()); |
| 653 | if (it == payload_type_frequencies_.end()) |
| 654 | return; |
| 655 | // TODO(bugs.webrtc.org/7135): Set payload_type_frequency earlier, when packet |
| 656 | // is parsed. |
| 657 | RtpPacketReceived packet_copy(packet); |
| 658 | packet_copy.set_payload_type_frequency(it->second); |
| 659 |
| 660 | rtp_receive_statistics_->OnRtpPacket(packet_copy); |
| 661 |
| 662 | RTPHeader header; |
| 663 | packet_copy.GetHeader(&header); |
| 664 |
| 665 | // Interpolates absolute capture timestamp RTP header extension. |
| 666 | header.extension.absolute_capture_time = |
| 667 | absolute_capture_time_interpolator_.OnReceivePacket( |
| 668 | AbsoluteCaptureTimeInterpolator::GetSource(header.ssrc, |
| 669 | header.arrOfCSRCs), |
| 670 | header.timestamp, |
| 671 | rtc::saturated_cast<uint32_t>(packet_copy.payload_type_frequency()), |
| 672 | header.extension.absolute_capture_time); |
| 673 |
| 674 | ReceivePacket(packet_copy.data(), packet_copy.size(), header); |
| 675 | } |
| 676 |
| 677 | void ChannelReceive::ReceivePacket(const uint8_t* packet, |
| 678 | size_t packet_length, |
| 679 | const RTPHeader& header) { |
| 680 | const uint8_t* payload = packet + header.headerLength; |
| 681 | RTC_DCHECK_GE(packet_length, header.headerLength); |
| 682 | size_t payload_length = packet_length - header.headerLength; |
| 683 |
| 684 | size_t payload_data_length = payload_length - header.paddingLength; |
| 685 |
| 686 | // E2EE Custom Audio Frame Decryption (This is optional). |
| 687 | // Keep this buffer around for the lifetime of the OnReceivedPayloadData call. |
| 688 | rtc::Buffer decrypted_audio_payload; |
| 689 | if (frame_decryptor_ != nullptr) { |
| 690 | const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize( |
| 691 | cricket::MEDIA_TYPE_AUDIO, payload_length); |
| 692 | decrypted_audio_payload.SetSize(max_plaintext_size); |
| 693 |
| 694 | const std::vector<uint32_t> csrcs(header.arrOfCSRCs, |
| 695 | header.arrOfCSRCs + header.numCSRCs); |
| 696 | const FrameDecryptorInterface::Result decrypt_result = |
| 697 | frame_decryptor_->Decrypt( |
| 698 | cricket::MEDIA_TYPE_AUDIO, csrcs, |
| 699 | /*additional_data=*/nullptr, |
| 700 | rtc::ArrayView<const uint8_t>(payload, payload_data_length), |
| 701 | decrypted_audio_payload); |
| 702 |
| 703 | if (decrypt_result.IsOk()) { |
| 704 | decrypted_audio_payload.SetSize(decrypt_result.bytes_written); |
| 705 | } else { |
| 706 | // Interpret failures as a silent frame. |
| 707 | decrypted_audio_payload.SetSize(0); |
| 708 | } |
| 709 |
| 710 | payload = decrypted_audio_payload.data(); |
| 711 | payload_data_length = decrypted_audio_payload.size(); |
| 712 | } else if (crypto_options_.sframe.require_frame_encryption) { |
| 713 | RTC_DLOG(LS_ERROR) |
| 714 | << "FrameDecryptor required but not set, dropping packet"; |
| 715 | payload_data_length = 0; |
| 716 | } |
| 717 |
| 718 | rtc::ArrayView<const uint8_t> payload_data(payload, payload_data_length); |
| 719 | if (frame_transformer_delegate_) { |
| 720 | // Asynchronously transform the received payload. After the payload is |
| 721 | // transformed, the delegate will call OnReceivedPayloadData to handle it. |
| 722 | char buf[1024]; |
| 723 | rtc::SimpleStringBuilder mime_type(buf); |
| 724 | auto it = payload_type_map_.find(header.payloadType); |
| 725 | mime_type << MediaTypeToString(cricket::MEDIA_TYPE_AUDIO) << "/" |
| 726 | << (it != payload_type_map_.end() ? it->second.name |
| 727 | : "x-unknown"); |
| 728 | frame_transformer_delegate_->Transform(payload_data, header, remote_ssrc_, |
| 729 | mime_type.str()); |
| 730 | } else { |
| 731 | OnReceivedPayloadData(payload_data, header); |
| 732 | } |
| 733 | } |
| 734 |
| 735 | void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) { |
| 736 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 737 | // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the |
| 738 | // network thread. |
| 739 |
| 740 | // Store playout timestamp for the received RTCP packet |
| 741 | UpdatePlayoutTimestamp(true, rtc::TimeMillis()); |
| 742 |
| 743 | // Deliver RTCP packet to RTP/RTCP module for parsing |
| 744 | rtp_rtcp_->IncomingRtcpPacket(rtc::MakeArrayView(data, length)); |
| 745 |
| 746 | absl::optional<TimeDelta> rtt = rtp_rtcp_->LastRtt(); |
| 747 | if (!rtt.has_value()) { |
| 748 | // Waiting for valid RTT. |
| 749 | return; |
| 750 | } |
| 751 |
| 752 | absl::optional<RtpRtcpInterface::SenderReportStats> last_sr = |
| 753 | rtp_rtcp_->GetSenderReportStats(); |
| 754 | if (!last_sr.has_value()) { |
| 755 | // Waiting for RTCP. |
| 756 | return; |
| 757 | } |
| 758 |
| 759 | { |
| 760 | MutexLock lock(&ts_stats_lock_); |
| 761 | ntp_estimator_.UpdateRtcpTimestamp(*rtt, last_sr->last_remote_timestamp, |
| 762 | last_sr->last_remote_rtp_timestamp); |
| 763 | absl::optional<int64_t> remote_to_local_clock_offset = |
| 764 | ntp_estimator_.EstimateRemoteToLocalClockOffset(); |
| 765 | if (remote_to_local_clock_offset.has_value()) { |
| 766 | capture_clock_offset_updater_.SetRemoteToLocalClockOffset( |
| 767 | *remote_to_local_clock_offset); |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 |
| 772 | int ChannelReceive::GetSpeechOutputLevelFullRange() const { |
| 773 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 774 | return _outputAudioLevel.LevelFullRange(); |
| 775 | } |
| 776 |
| 777 | double ChannelReceive::GetTotalOutputEnergy() const { |
| 778 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 779 | return _outputAudioLevel.TotalEnergy(); |
| 780 | } |
| 781 |
| 782 | double ChannelReceive::GetTotalOutputDuration() const { |
| 783 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 784 | return _outputAudioLevel.TotalDuration(); |
| 785 | } |
| 786 |
| 787 | void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) { |
| 788 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 789 | MutexLock lock(&volume_settings_mutex_); |
| 790 | _outputGain = scaling; |
| 791 | } |
| 792 |
| 793 | void ChannelReceive::RegisterReceiverCongestionControlObjects( |
| 794 | PacketRouter* packet_router) { |
| 795 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 796 | RTC_DCHECK(packet_router); |
| 797 | RTC_DCHECK(!packet_router_); |
| 798 | constexpr bool remb_candidate = false; |
| 799 | packet_router->AddReceiveRtpModule(rtp_rtcp_.get(), remb_candidate); |
| 800 | packet_router_ = packet_router; |
| 801 | } |
| 802 |
| 803 | void ChannelReceive::ResetReceiverCongestionControlObjects() { |
| 804 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 805 | RTC_DCHECK(packet_router_); |
| 806 | packet_router_->RemoveReceiveRtpModule(rtp_rtcp_.get()); |
| 807 | packet_router_ = nullptr; |
| 808 | } |
| 809 |
| 810 | CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const { |
| 811 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 812 | CallReceiveStatistics stats; |
| 813 |
| 814 | // The jitter statistics is updated for each received RTP packet and is based |
| 815 | // on received packets. |
| 816 | RtpReceiveStats rtp_stats; |
| 817 | StreamStatistician* statistician = |
| 818 | rtp_receive_statistics_->GetStatistician(remote_ssrc_); |
| 819 | if (statistician) { |
| 820 | rtp_stats = statistician->GetStats(); |
| 821 | } |
| 822 |
| 823 | stats.cumulativeLost = rtp_stats.packets_lost; |
| 824 | stats.jitterSamples = rtp_stats.jitter; |
| 825 |
| 826 | // Data counters. |
| 827 | if (statistician) { |
| 828 | stats.payload_bytes_received = rtp_stats.packet_counter.payload_bytes; |
| 829 |
| 830 | stats.header_and_padding_bytes_received = |
| 831 | rtp_stats.packet_counter.header_bytes + |
| 832 | rtp_stats.packet_counter.padding_bytes; |
| 833 | stats.packetsReceived = rtp_stats.packet_counter.packets; |
| 834 | stats.last_packet_received = rtp_stats.last_packet_received; |
| 835 | } else { |
| 836 | stats.payload_bytes_received = 0; |
| 837 | stats.header_and_padding_bytes_received = 0; |
| 838 | stats.packetsReceived = 0; |
| 839 | stats.last_packet_received = absl::nullopt; |
| 840 | } |
| 841 |
| 842 | { |
| 843 | MutexLock lock(&rtcp_counter_mutex_); |
| 844 | stats.nacks_sent = rtcp_packet_type_counter_.nack_packets; |
| 845 | } |
| 846 |
| 847 | // Timestamps. |
| 848 | { |
| 849 | MutexLock lock(&ts_stats_lock_); |
| 850 | stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_; |
| 851 | } |
| 852 |
| 853 | absl::optional<RtpRtcpInterface::SenderReportStats> rtcp_sr_stats = |
| 854 | rtp_rtcp_->GetSenderReportStats(); |
| 855 | if (rtcp_sr_stats.has_value()) { |
| 856 | stats.last_sender_report_timestamp_ms = |
| 857 | rtcp_sr_stats->last_arrival_timestamp.ToMs() - |
| 858 | rtc::kNtpJan1970Millisecs; |
| 859 | stats.last_sender_report_remote_timestamp_ms = |
| 860 | rtcp_sr_stats->last_remote_timestamp.ToMs() - rtc::kNtpJan1970Millisecs; |
| 861 | stats.sender_reports_packets_sent = rtcp_sr_stats->packets_sent; |
| 862 | stats.sender_reports_bytes_sent = rtcp_sr_stats->bytes_sent; |
| 863 | stats.sender_reports_reports_count = rtcp_sr_stats->reports_count; |
| 864 | } |
| 865 |
| 866 | absl::optional<RtpRtcpInterface::NonSenderRttStats> non_sender_rtt_stats = |
| 867 | rtp_rtcp_->GetNonSenderRttStats(); |
| 868 | if (non_sender_rtt_stats.has_value()) { |
| 869 | stats.round_trip_time = non_sender_rtt_stats->round_trip_time; |
| 870 | stats.round_trip_time_measurements = |
| 871 | non_sender_rtt_stats->round_trip_time_measurements; |
| 872 | stats.total_round_trip_time = non_sender_rtt_stats->total_round_trip_time; |
| 873 | } |
| 874 |
| 875 | return stats; |
| 876 | } |
| 877 |
| 878 | void ChannelReceive::SetNACKStatus(bool enable, int max_packets) { |
| 879 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 880 | // None of these functions can fail. |
| 881 | if (enable) { |
| 882 | rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets); |
| 883 | acm_receiver_.EnableNack(max_packets); |
| 884 | } else { |
| 885 | rtp_receive_statistics_->SetMaxReorderingThreshold( |
| 886 | kDefaultMaxReorderingThreshold); |
| 887 | acm_receiver_.DisableNack(); |
| 888 | } |
| 889 | } |
| 890 |
| 891 | void ChannelReceive::SetNonSenderRttMeasurement(bool enabled) { |
| 892 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 893 | rtp_rtcp_->SetNonSenderRttMeasurement(enabled); |
| 894 | } |
| 895 |
| 896 | // Called when we are missing one or more packets. |
| 897 | int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers, |
| 898 | int length) { |
| 899 | return rtp_rtcp_->SendNACK(sequence_numbers, length); |
| 900 | } |
| 901 |
| 902 | void ChannelReceive::RtcpPacketTypesCounterUpdated( |
| 903 | uint32_t ssrc, |
| 904 | const RtcpPacketTypeCounter& packet_counter) { |
| 905 | if (ssrc != remote_ssrc_) { |
| 906 | return; |
| 907 | } |
| 908 | MutexLock lock(&rtcp_counter_mutex_); |
| 909 | rtcp_packet_type_counter_ = packet_counter; |
| 910 | } |
| 911 |
| 912 | void ChannelReceive::SetAssociatedSendChannel( |
| 913 | const ChannelSendInterface* channel) { |
| 914 | RTC_DCHECK_RUN_ON(&network_thread_checker_); |
| 915 | associated_send_channel_ = channel; |
| 916 | } |
| 917 |
| 918 | void ChannelReceive::SetDepacketizerToDecoderFrameTransformer( |
| 919 | rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) { |
| 920 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 921 | if (!frame_transformer) { |
| 922 | RTC_DCHECK_NOTREACHED() << "Not setting the transformer?"; |
| 923 | return; |
| 924 | } |
| 925 | if (frame_transformer_delegate_) { |
| 926 | // Depending on when the channel is created, the transformer might be set |
| 927 | // twice. Don't replace the delegate if it was already initialized. |
| 928 | // TODO(crbug.com/webrtc/15674): Prevent multiple calls during |
| 929 | // reconfiguration. |
| 930 | RTC_CHECK_EQ(frame_transformer_delegate_->FrameTransformer(), |
| 931 | frame_transformer); |
| 932 | return; |
| 933 | } |
| 934 |
| 935 | InitFrameTransformerDelegate(std::move(frame_transformer)); |
| 936 | } |
| 937 |
| 938 | void ChannelReceive::SetFrameDecryptor( |
| 939 | rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) { |
| 940 | // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread. |
| 941 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 942 | frame_decryptor_ = std::move(frame_decryptor); |
| 943 | } |
| 944 |
| 945 | void ChannelReceive::OnLocalSsrcChange(uint32_t local_ssrc) { |
| 946 | // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread. |
| 947 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 948 | rtp_rtcp_->SetLocalSsrc(local_ssrc); |
| 949 | } |
| 950 |
| 951 | uint32_t ChannelReceive::GetLocalSsrc() const { |
| 952 | // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread. |
| 953 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 954 | return rtp_rtcp_->local_media_ssrc(); |
| 955 | } |
| 956 |
| 957 | NetworkStatistics ChannelReceive::GetNetworkStatistics( |
| 958 | bool get_and_clear_legacy_stats) const { |
| 959 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 960 | NetworkStatistics stats; |
| 961 | acm_receiver_.GetNetworkStatistics(&stats, get_and_clear_legacy_stats); |
| 962 | return stats; |
| 963 | } |
| 964 |
| 965 | AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const { |
| 966 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 967 | AudioDecodingCallStats stats; |
| 968 | acm_receiver_.GetDecodingCallStatistics(&stats); |
| 969 | return stats; |
| 970 | } |
| 971 |
| 972 | uint32_t ChannelReceive::GetDelayEstimate() const { |
| 973 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 974 | // Return the current jitter buffer delay + playout delay. |
| 975 | return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_; |
| 976 | } |
| 977 |
| 978 | bool ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) { |
| 979 | // TODO(bugs.webrtc.org/11993): This should run on the network thread. |
| 980 | // We get here via RtpStreamsSynchronizer. Once that's done, many (all?) of |
| 981 | // these locks aren't needed. |
| 982 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 983 | // Limit to range accepted by both VoE and ACM, so we're at least getting as |
| 984 | // close as possible, instead of failing. |
| 985 | delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs, |
| 986 | kVoiceEngineMaxMinPlayoutDelayMs); |
| 987 | if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) { |
| 988 | RTC_DLOG(LS_ERROR) |
| 989 | << "SetMinimumPlayoutDelay() failed to set min playout delay"; |
| 990 | return false; |
| 991 | } |
| 992 | return true; |
| 993 | } |
| 994 |
| 995 | bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp, |
| 996 | int64_t* time_ms) const { |
| 997 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 998 | if (!playout_timestamp_rtp_time_ms_) |
| 999 | return false; |
| 1000 | *rtp_timestamp = playout_timestamp_rtp_; |
| 1001 | *time_ms = playout_timestamp_rtp_time_ms_.value(); |
| 1002 | return true; |
| 1003 | } |
| 1004 |
| 1005 | void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms, |
| 1006 | int64_t time_ms) { |
| 1007 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 1008 | playout_timestamp_ntp_ = ntp_timestamp_ms; |
| 1009 | playout_timestamp_ntp_time_ms_ = time_ms; |
| 1010 | } |
| 1011 |
| 1012 | absl::optional<int64_t> |
| 1013 | ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const { |
| 1014 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 1015 | if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_) |
| 1016 | return absl::nullopt; |
| 1017 |
| 1018 | int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_; |
| 1019 | return *playout_timestamp_ntp_ + elapsed_ms; |
| 1020 | } |
| 1021 |
| 1022 | bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) { |
| 1023 | event_log_->Log( |
| 1024 | std::make_unique<RtcEventNetEqSetMinimumDelay>(remote_ssrc_, delay_ms)); |
| 1025 | return acm_receiver_.SetBaseMinimumDelayMs(delay_ms); |
| 1026 | } |
| 1027 |
| 1028 | int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const { |
| 1029 | return acm_receiver_.GetBaseMinimumDelayMs(); |
| 1030 | } |
| 1031 |
| 1032 | absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const { |
| 1033 | // TODO(bugs.webrtc.org/11993): This should run on the network thread. |
| 1034 | // We get here via RtpStreamsSynchronizer. Once that's done, many of |
| 1035 | // these locks aren't needed. |
| 1036 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 1037 | Syncable::Info info; |
| 1038 | absl::optional<RtpRtcpInterface::SenderReportStats> last_sr = |
| 1039 | rtp_rtcp_->GetSenderReportStats(); |
| 1040 | if (!last_sr.has_value()) { |
| 1041 | return absl::nullopt; |
| 1042 | } |
| 1043 | info.capture_time_ntp_secs = last_sr->last_remote_timestamp.seconds(); |
| 1044 | info.capture_time_ntp_frac = last_sr->last_remote_timestamp.fractions(); |
| 1045 | info.capture_time_source_clock = last_sr->last_remote_rtp_timestamp; |
| 1046 |
| 1047 | if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) { |
| 1048 | return absl::nullopt; |
| 1049 | } |
| 1050 | info.latest_received_capture_timestamp = *last_received_rtp_timestamp_; |
| 1051 | info.latest_receive_time_ms = *last_received_rtp_system_time_ms_; |
| 1052 |
| 1053 | int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs(); |
| 1054 | info.current_delay_ms = jitter_buffer_delay + playout_delay_ms_; |
| 1055 |
| 1056 | return info; |
| 1057 | } |
| 1058 |
| 1059 | void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) { |
| 1060 | RTC_DCHECK_RUN_ON(&worker_thread_checker_); |
| 1061 | // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the |
| 1062 | // network thread. Once that's done, we won't need video_sync_lock_. |
| 1063 |
| 1064 | jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp(); |
| 1065 |
| 1066 | if (!jitter_buffer_playout_timestamp_) { |
| 1067 | // This can happen if this channel has not received any RTP packets. In |
| 1068 | // this case, NetEq is not capable of computing a playout timestamp. |
| 1069 | return; |
| 1070 | } |
| 1071 |
| 1072 | uint16_t delay_ms = 0; |
| 1073 | if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) { |
| 1074 | RTC_DLOG(LS_WARNING) |
| 1075 | << "ChannelReceive::UpdatePlayoutTimestamp() failed to read" |
| 1076 | " playout delay from the ADM"; |
| 1077 | return; |
| 1078 | } |
| 1079 |
| 1080 | RTC_DCHECK(jitter_buffer_playout_timestamp_); |
| 1081 | uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_; |
| 1082 |
| 1083 | // Remove the playout delay. |
| 1084 | playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000)); |
| 1085 |
| 1086 | if (!rtcp && playout_timestamp != playout_timestamp_rtp_) { |
| 1087 | playout_timestamp_rtp_ = playout_timestamp; |
| 1088 | playout_timestamp_rtp_time_ms_ = now_ms; |
| 1089 | } |
| 1090 | playout_delay_ms_ = delay_ms; |
| 1091 | } |
| 1092 |
| 1093 | int ChannelReceive::GetRtpTimestampRateHz() const { |
| 1094 | const auto decoder = acm_receiver_.LastDecoder(); |
| 1095 | // Default to the playout frequency if we've not gotten any packets yet. |
| 1096 | // TODO(ossu): Zero clockrate can only happen if we've added an external |
| 1097 | // decoder for a format we don't support internally. Remove once that way of |
| 1098 | // adding decoders is gone! |
| 1099 | // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it |
| 1100 | // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample |
| 1101 | // rate, which is not always the same thing. |
| 1102 | return (decoder && decoder->second.clockrate_hz != 0) |
| 1103 | ? decoder->second.clockrate_hz |
| 1104 | : acm_receiver_.last_output_sample_rate_hz(); |
| 1105 | } |
| 1106 |
| 1107 | } // namespace |
| 1108 |
| 1109 | std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive( |
| 1110 | Clock* clock, |
| 1111 | NetEqFactory* neteq_factory, |
| 1112 | AudioDeviceModule* audio_device_module, |
| 1113 | Transport* rtcp_send_transport, |
| 1114 | RtcEventLog* rtc_event_log, |
| 1115 | uint32_t local_ssrc, |
| 1116 | uint32_t remote_ssrc, |
| 1117 | size_t jitter_buffer_max_packets, |
| 1118 | bool jitter_buffer_fast_playout, |
| 1119 | int jitter_buffer_min_delay_ms, |
| 1120 | bool enable_non_sender_rtt, |
| 1121 | rtc::scoped_refptr<AudioDecoderFactory> decoder_factory, |
| 1122 | absl::optional<AudioCodecPairId> codec_pair_id, |
| 1123 | rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor, |
| 1124 | const webrtc::CryptoOptions& crypto_options, |
| 1125 | rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) { |
| 1126 | return std::make_unique<ChannelReceive>( |
| 1127 | clock, neteq_factory, audio_device_module, rtcp_send_transport, |
| 1128 | rtc_event_log, local_ssrc, remote_ssrc, jitter_buffer_max_packets, |
| 1129 | jitter_buffer_fast_playout, jitter_buffer_min_delay_ms, |
| 1130 | enable_non_sender_rtt, decoder_factory, codec_pair_id, |
| 1131 | std::move(frame_decryptor), crypto_options, std::move(frame_transformer)); |
| 1132 | } |
| 1133 |
| 1134 | } // namespace voe |
| 1135 | } // namespace webrtc |
| 1136 |