blob: f2fd34ab16c5e722fc6d937e614c9b2c57afdf02 [file] [log] [blame]
Niels Möller530ead42018-10-04 14:28:39 +02001/*
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_receive.h"
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
Niels Möllera8370302019-09-02 15:16:49 +020020#include "api/crypto/frame_decryptor_interface.h"
Marina Ciocea3e9af7f2020-04-01 07:46:16 +020021#include "api/frame_transformer_interface.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020022#include "api/rtc_event_log/rtc_event_log.h"
Artem Titovd15a5752021-02-10 14:31:24 +010023#include "api/sequence_checker.h"
Tommie2e04642021-06-09 16:11:11 +020024#include "api/task_queue/task_queue_base.h"
Niels Möller349ade32018-11-16 09:50:42 +010025#include "audio/audio_level.h"
Marina Ciocea48623202020-04-01 10:19:44 +020026#include "audio/channel_receive_frame_transformer_delegate.h"
Niels Möller530ead42018-10-04 14:28:39 +020027#include "audio/channel_send.h"
28#include "audio/utility/audio_frame_operations.h"
29#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möllered44f542019-07-30 15:15:59 +020030#include "modules/audio_coding/acm2/acm_receiver.h"
Niels Möller530ead42018-10-04 14:28:39 +020031#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
32#include "modules/audio_device/include/audio_device.h"
33#include "modules/pacing/packet_router.h"
34#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010035#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
Minyue Li63b30952021-05-19 14:38:25 +020036#include "modules/rtp_rtcp/source/absolute_capture_time_interpolator.h"
37#include "modules/rtp_rtcp/source/capture_clock_offset_updater.h"
Yves Gerey988cc082018-10-23 12:03:01 +020038#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010040#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Tomas Gunnarssonfae05622020-06-03 08:54:39 +020041#include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
Niels Möller530ead42018-10-04 14:28:39 +020042#include "rtc_base/checks.h"
Niels Möller530ead42018-10-04 14:28:39 +020043#include "rtc_base/format_macros.h"
44#include "rtc_base/location.h"
45#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010046#include "rtc_base/numerics/safe_minmax.h"
47#include "rtc_base/race_checker.h"
Markus Handell62872802020-07-06 15:15:07 +020048#include "rtc_base/synchronization/mutex.h"
Tommi02df2eb2021-05-31 12:57:53 +020049#include "rtc_base/system/no_unique_address.h"
Tommie2e04642021-06-09 16:11:11 +020050#include "rtc_base/task_utils/pending_task_safety_flag.h"
51#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020053#include "system_wrappers/include/metrics.h"
54
55namespace webrtc {
56namespace voe {
57
58namespace {
59
60constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020061
62// Video Sync.
63constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
64constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
65
Niels Möllered44f542019-07-30 15:15:59 +020066AudioCodingModule::Config AcmConfig(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010067 NetEqFactory* neteq_factory,
Niels Möllered44f542019-07-30 15:15:59 +020068 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
69 absl::optional<AudioCodecPairId> codec_pair_id,
70 size_t jitter_buffer_max_packets,
71 bool jitter_buffer_fast_playout) {
72 AudioCodingModule::Config acm_config;
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010073 acm_config.neteq_factory = neteq_factory;
Niels Möllered44f542019-07-30 15:15:59 +020074 acm_config.decoder_factory = decoder_factory;
75 acm_config.neteq_config.codec_pair_id = codec_pair_id;
76 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
77 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
78 acm_config.neteq_config.enable_muted_state = true;
79
80 return acm_config;
81}
82
Jakob Ivarssone54914a2021-07-01 11:16:05 +020083class ChannelReceive : public ChannelReceiveInterface,
84 public RtcpPacketTypeCounterObserver {
Niels Möller349ade32018-11-16 09:50:42 +010085 public:
86 // Used for receive streams.
Marina Ciocea3e9af7f2020-04-01 07:46:16 +020087 ChannelReceive(
88 Clock* clock,
Marina Ciocea3e9af7f2020-04-01 07:46:16 +020089 NetEqFactory* neteq_factory,
90 AudioDeviceModule* audio_device_module,
91 Transport* rtcp_send_transport,
92 RtcEventLog* rtc_event_log,
93 uint32_t local_ssrc,
94 uint32_t remote_ssrc,
95 size_t jitter_buffer_max_packets,
96 bool jitter_buffer_fast_playout,
97 int jitter_buffer_min_delay_ms,
98 bool jitter_buffer_enable_rtx_handling,
Ivo Creusen2562cf02021-09-03 14:51:22 +000099 bool enable_non_sender_rtt,
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200100 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
101 absl::optional<AudioCodecPairId> codec_pair_id,
102 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
103 const webrtc::CryptoOptions& crypto_options,
104 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer);
Niels Möller349ade32018-11-16 09:50:42 +0100105 ~ChannelReceive() override;
106
107 void SetSink(AudioSinkInterface* sink) override;
108
109 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
110
111 // API methods
112
113 void StartPlayout() override;
114 void StopPlayout() override;
115
116 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000117 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
118 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100119
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100120 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100121
122 // RtpPacketSinkInterface.
123 void OnRtpPacket(const RtpPacketReceived& packet) override;
124
125 // Muting, Volume and Level.
126 void SetChannelOutputVolumeScaling(float scaling) override;
127 int GetSpeechOutputLevelFullRange() const override;
128 // See description of "totalAudioEnergy" in the WebRTC stats spec:
129 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
130 double GetTotalOutputEnergy() const override;
131 double GetTotalOutputDuration() const override;
132
133 // Stats.
Niels Möller6b4d9622020-09-14 10:47:50 +0200134 NetworkStatistics GetNetworkStatistics(
135 bool get_and_clear_legacy_stats) const override;
Niels Möller349ade32018-11-16 09:50:42 +0100136 AudioDecodingCallStats GetDecodingCallStatistics() const override;
137
138 // Audio+Video Sync.
139 uint32_t GetDelayEstimate() const override;
Ivo Creusenbef7b052020-09-08 16:30:25 +0200140 bool SetMinimumPlayoutDelay(int delayMs) override;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200141 bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
142 int64_t* time_ms) const override;
143 void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
144 int64_t time_ms) override;
145 absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs(
146 int64_t now_ms) const override;
Niels Möller349ade32018-11-16 09:50:42 +0100147
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100148 // Audio quality.
149 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
150 int GetBaseMinimumPlayoutDelayMs() const override;
151
Niels Möller349ade32018-11-16 09:50:42 +0100152 // Produces the transport-related timestamps; current_delay_ms is left unset.
153 absl::optional<Syncable::Info> GetSyncInfo() const override;
154
Niels Möller349ade32018-11-16 09:50:42 +0100155 void RegisterReceiverCongestionControlObjects(
156 PacketRouter* packet_router) override;
157 void ResetReceiverCongestionControlObjects() override;
158
159 CallReceiveStatistics GetRTCPStatistics() const override;
160 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
Ivo Creusen2562cf02021-09-03 14:51:22 +0000161 void SetNonSenderRttMeasurement(bool enabled) override;
Niels Möller349ade32018-11-16 09:50:42 +0100162
163 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
164 int sample_rate_hz,
165 AudioFrame* audio_frame) override;
166
167 int PreferredSampleRate() const override;
168
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530169 void SetSourceTracker(SourceTracker* source_tracker) override;
170
Niels Möller349ade32018-11-16 09:50:42 +0100171 // Associate to a send channel.
172 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100173 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100174
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200175 // Sets a frame transformer between the depacketizer and the decoder, to
176 // transform the received frames before decoding them.
177 void SetDepacketizerToDecoderFrameTransformer(
178 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)
179 override;
180
Tommie0972822021-06-14 08:11:10 +0200181 void SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface>
182 frame_decryptor) override;
183
Tommi08be9ba2021-06-15 23:01:57 +0200184 void OnLocalSsrcChange(uint32_t local_ssrc) override;
185 uint32_t GetLocalSsrc() const override;
186
Jakob Ivarssone54914a2021-07-01 11:16:05 +0200187 void RtcpPacketTypesCounterUpdated(
188 uint32_t ssrc,
189 const RtcpPacketTypeCounter& packet_counter) override;
190
Niels Möller349ade32018-11-16 09:50:42 +0100191 private:
Niels Möllered44f542019-07-30 15:15:59 +0200192 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100193 size_t packet_length,
Tommie2e04642021-06-09 16:11:11 +0200194 const RTPHeader& header)
195 RTC_RUN_ON(worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100196 int ResendPackets(const uint16_t* sequence_numbers, int length);
Tommie2e04642021-06-09 16:11:11 +0200197 void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms)
198 RTC_RUN_ON(worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100199
200 int GetRtpTimestampRateHz() const;
201 int64_t GetRTT() const;
202
Niels Möllered44f542019-07-30 15:15:59 +0200203 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
Tommie2e04642021-06-09 16:11:11 +0200204 const RTPHeader& rtpHeader)
205 RTC_RUN_ON(worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100206
Marina Ciocea48623202020-04-01 10:19:44 +0200207 void InitFrameTransformerDelegate(
Tommie2e04642021-06-09 16:11:11 +0200208 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)
209 RTC_RUN_ON(worker_thread_checker_);
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100210
Niels Möller349ade32018-11-16 09:50:42 +0100211 // Thread checkers document and lock usage of some methods to specific threads
212 // we know about. The goal is to eventually split up voe::ChannelReceive into
213 // parts with single-threaded semantics, and thereby reduce the need for
214 // locks.
Tommi02df2eb2021-05-31 12:57:53 +0200215 RTC_NO_UNIQUE_ADDRESS SequenceChecker worker_thread_checker_;
216 RTC_NO_UNIQUE_ADDRESS SequenceChecker network_thread_checker_;
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200217
Tommie2e04642021-06-09 16:11:11 +0200218 TaskQueueBase* const worker_thread_;
219 ScopedTaskSafety worker_safety_;
220
Niels Möller349ade32018-11-16 09:50:42 +0100221 // Methods accessed from audio and video threads are checked for sequential-
222 // only access. We don't necessarily own and control these threads, so thread
223 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
224 // audio thread to another, but access is still sequential.
225 rtc::RaceChecker audio_thread_race_checker_;
Markus Handell62872802020-07-06 15:15:07 +0200226 Mutex callback_mutex_;
227 Mutex volume_settings_mutex_;
Niels Möller349ade32018-11-16 09:50:42 +0100228
Tommie2e04642021-06-09 16:11:11 +0200229 bool playing_ RTC_GUARDED_BY(worker_thread_checker_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100230
231 RtcEventLog* const event_log_;
232
233 // Indexed by payload type.
234 std::map<uint8_t, int> payload_type_frequencies_;
235
236 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200237 std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_;
Niels Möller349ade32018-11-16 09:50:42 +0100238 const uint32_t remote_ssrc_;
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530239 SourceTracker* source_tracker_ = nullptr;
Niels Möller349ade32018-11-16 09:50:42 +0100240
Chen Xing054e3bb2019-08-02 10:29:26 +0000241 // Info for GetSyncInfo is updated on network or worker thread, and queried on
242 // the worker thread.
Niels Möller349ade32018-11-16 09:50:42 +0100243 absl::optional<uint32_t> last_received_rtp_timestamp_
Tommie2e04642021-06-09 16:11:11 +0200244 RTC_GUARDED_BY(&worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100245 absl::optional<int64_t> last_received_rtp_system_time_ms_
Tommie2e04642021-06-09 16:11:11 +0200246 RTC_GUARDED_BY(&worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100247
Niels Möllered44f542019-07-30 15:15:59 +0200248 // The AcmReceiver is thread safe, using its own lock.
249 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100250 AudioSinkInterface* audio_sink_ = nullptr;
251 AudioLevel _outputAudioLevel;
252
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530253 Clock* const clock_;
Niels Möller349ade32018-11-16 09:50:42 +0100254 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
255
256 // Timestamp of the audio pulled from NetEq.
257 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
258
Tommie2e04642021-06-09 16:11:11 +0200259 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(worker_thread_checker_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200260 absl::optional<int64_t> playout_timestamp_rtp_time_ms_
Tommie2e04642021-06-09 16:11:11 +0200261 RTC_GUARDED_BY(worker_thread_checker_);
262 uint32_t playout_delay_ms_ RTC_GUARDED_BY(worker_thread_checker_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200263 absl::optional<int64_t> playout_timestamp_ntp_
Tommie2e04642021-06-09 16:11:11 +0200264 RTC_GUARDED_BY(worker_thread_checker_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200265 absl::optional<int64_t> playout_timestamp_ntp_time_ms_
Tommie2e04642021-06-09 16:11:11 +0200266 RTC_GUARDED_BY(worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100267
Markus Handell62872802020-07-06 15:15:07 +0200268 mutable Mutex ts_stats_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100269
270 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
271 // The rtp timestamp of the first played out audio frame.
272 int64_t capture_start_rtp_time_stamp_;
273 // The capture ntp time (in local timebase) of the first played out audio
274 // frame.
275 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
276
Niels Möller349ade32018-11-16 09:50:42 +0100277 AudioDeviceModule* _audioDeviceModulePtr;
Markus Handell62872802020-07-06 15:15:07 +0200278 float _outputGain RTC_GUARDED_BY(volume_settings_mutex_);
Niels Möller349ade32018-11-16 09:50:42 +0100279
Niels Möllerdced9f62018-11-19 10:27:07 +0100280 const ChannelSendInterface* associated_send_channel_
Tommi02df2eb2021-05-31 12:57:53 +0200281 RTC_GUARDED_BY(network_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100282
283 PacketRouter* packet_router_ = nullptr;
284
Artem Titovc8421c42021-02-02 10:57:19 +0100285 SequenceChecker construction_thread_;
Niels Möller349ade32018-11-16 09:50:42 +0100286
Niels Möller349ade32018-11-16 09:50:42 +0100287 // E2EE Audio Frame Decryption
Tommie0972822021-06-14 08:11:10 +0200288 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_
289 RTC_GUARDED_BY(worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100290 webrtc::CryptoOptions crypto_options_;
Minyue Lib506fee2020-02-11 13:04:02 +0100291
Tommie0972822021-06-14 08:11:10 +0200292 webrtc::AbsoluteCaptureTimeInterpolator absolute_capture_time_interpolator_
293 RTC_GUARDED_BY(worker_thread_checker_);
Minyue Li63b30952021-05-19 14:38:25 +0200294
295 webrtc::CaptureClockOffsetUpdater capture_clock_offset_updater_;
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200296
Marina Ciocea48623202020-04-01 10:19:44 +0200297 rtc::scoped_refptr<ChannelReceiveFrameTransformerDelegate>
298 frame_transformer_delegate_;
Tommi3cc68ec2021-06-09 19:30:41 +0200299
300 // Counter that's used to control the frequency of reporting histograms
301 // from the `GetAudioFrameWithInfo` callback.
302 int audio_frame_interval_count_ RTC_GUARDED_BY(audio_thread_race_checker_) =
303 0;
304 // Controls how many callbacks we let pass by before reporting callback stats.
305 // A value of 100 means 100 callbacks, each one of which represents 10ms worth
306 // of data, so the stats reporting frequency will be 1Hz (modulo failures).
307 constexpr static int kHistogramReportingInterval = 100;
Jakob Ivarssone54914a2021-07-01 11:16:05 +0200308
309 mutable Mutex rtcp_counter_mutex_;
310 RtcpPacketTypeCounter rtcp_packet_type_counter_
311 RTC_GUARDED_BY(rtcp_counter_mutex_);
Niels Möller349ade32018-11-16 09:50:42 +0100312};
Niels Möller530ead42018-10-04 14:28:39 +0200313
Niels Möllered44f542019-07-30 15:15:59 +0200314void ChannelReceive::OnReceivedPayloadData(
315 rtc::ArrayView<const uint8_t> payload,
316 const RTPHeader& rtpHeader) {
Tommie2e04642021-06-09 16:11:11 +0200317 if (!playing_) {
Niels Möller530ead42018-10-04 14:28:39 +0200318 // Avoid inserting into NetEQ when we are not playing. Count the
319 // packet as discarded.
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530320
321 // If we have a source_tracker_, tell it that the frame has been
322 // "delivered". Normally, this happens in AudioReceiveStream when audio
323 // frames are pulled out, but when playout is muted, nothing is pulling
324 // frames. The downside of this approach is that frames delivered this way
325 // won't be delayed for playout, and therefore will be unsynchronized with
326 // (a) audio delay when playing and (b) any audio/video synchronization. But
327 // the alternative is that muting playout also stops the SourceTracker from
328 // updating RtpSource information.
329 if (source_tracker_) {
330 RtpPacketInfos::vector_type packet_vector = {
Johannes Kronf7de74c2021-04-30 13:10:56 +0200331 RtpPacketInfo(rtpHeader, clock_->CurrentTime())};
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530332 source_tracker_->OnFrameDelivered(RtpPacketInfos(packet_vector));
333 }
334
Niels Möllered44f542019-07-30 15:15:59 +0200335 return;
Niels Möller530ead42018-10-04 14:28:39 +0200336 }
337
338 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200339 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200340 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
341 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200342 return;
Niels Möller530ead42018-10-04 14:28:39 +0200343 }
344
345 int64_t round_trip_time = 0;
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200346 rtp_rtcp_->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
Niels Möller530ead42018-10-04 14:28:39 +0200347
Niels Möllered44f542019-07-30 15:15:59 +0200348 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200349 if (!nack_list.empty()) {
350 // Can't use nack_list.data() since it's not supported by all
351 // compilers.
352 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
353 }
Niels Möller530ead42018-10-04 14:28:39 +0200354}
355
Marina Ciocea48623202020-04-01 10:19:44 +0200356void ChannelReceive::InitFrameTransformerDelegate(
357 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
358 RTC_DCHECK(frame_transformer);
359 RTC_DCHECK(!frame_transformer_delegate_);
Tommie2e04642021-06-09 16:11:11 +0200360 RTC_DCHECK(worker_thread_->IsCurrent());
Marina Ciocea48623202020-04-01 10:19:44 +0200361
Marina Cioceafc23cc02020-04-02 12:10:03 +0200362 // Pass a callback to ChannelReceive::OnReceivedPayloadData, to be called by
363 // the delegate to receive transformed audio.
Marina Ciocea48623202020-04-01 10:19:44 +0200364 ChannelReceiveFrameTransformerDelegate::ReceiveFrameCallback
365 receive_audio_callback = [this](rtc::ArrayView<const uint8_t> packet,
366 const RTPHeader& header) {
Tommie2e04642021-06-09 16:11:11 +0200367 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Marina Cioceafc23cc02020-04-02 12:10:03 +0200368 OnReceivedPayloadData(packet, header);
Marina Ciocea48623202020-04-01 10:19:44 +0200369 };
370 frame_transformer_delegate_ =
Tomas Gunnarssonc1d58912021-04-22 19:21:43 +0200371 rtc::make_ref_counted<ChannelReceiveFrameTransformerDelegate>(
Marina Ciocea48623202020-04-01 10:19:44 +0200372 std::move(receive_audio_callback), std::move(frame_transformer),
Tommie2e04642021-06-09 16:11:11 +0200373 worker_thread_);
Marina Ciocea48623202020-04-01 10:19:44 +0200374 frame_transformer_delegate_->Init();
375}
376
Niels Möller530ead42018-10-04 14:28:39 +0200377AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
378 int sample_rate_hz,
379 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100380 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200381 audio_frame->sample_rate_hz_ = sample_rate_hz;
382
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200383 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100384
Niels Möller530ead42018-10-04 14:28:39 +0200385 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
386 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200387 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
388 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200389 RTC_DLOG(LS_ERROR)
390 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
391 // In all likelihood, the audio in this frame is garbage. We return an
392 // error so that the audio mixer module doesn't add it to the mix. As
393 // a result, it won't be played out and the actions skipped here are
394 // irrelevant.
395 return AudioMixer::Source::AudioFrameInfo::kError;
396 }
397
398 if (muted) {
399 // TODO(henrik.lundin): We should be able to do better than this. But we
400 // will have to go through all the cases below where the audio samples may
401 // be used, and handle the muted case in some way.
402 AudioFrameOperations::Mute(audio_frame);
403 }
404
405 {
406 // Pass the audio buffers to an optional sink callback, before applying
407 // scaling/panning, as that applies to the mix operation.
408 // External recipients of the audio (e.g. via AudioTrack), will do their
409 // own mixing/dynamic processing.
Markus Handell62872802020-07-06 15:15:07 +0200410 MutexLock lock(&callback_mutex_);
Niels Möller530ead42018-10-04 14:28:39 +0200411 if (audio_sink_) {
412 AudioSinkInterface::Data data(
413 audio_frame->data(), audio_frame->samples_per_channel_,
414 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
415 audio_frame->timestamp_);
416 audio_sink_->OnData(data);
417 }
418 }
419
420 float output_gain = 1.0f;
421 {
Markus Handell62872802020-07-06 15:15:07 +0200422 MutexLock lock(&volume_settings_mutex_);
Niels Möller530ead42018-10-04 14:28:39 +0200423 output_gain = _outputGain;
424 }
425
426 // Output volume scaling
427 if (output_gain < 0.99f || output_gain > 1.01f) {
428 // TODO(solenberg): Combine with mute state - this can cause clicks!
429 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
430 }
431
432 // Measure audio level (0-9)
Artem Titovb0ea6372021-07-26 11:47:07 +0200433 // TODO(henrik.lundin) Use the `muted` information here too.
434 // TODO(deadbeef): Use RmsLevel for `_outputAudioLevel` (see
Niels Möller530ead42018-10-04 14:28:39 +0200435 // https://crbug.com/webrtc/7517).
436 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
437
438 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
439 // The first frame with a valid rtp timestamp.
440 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
441 }
442
443 if (capture_start_rtp_time_stamp_ >= 0) {
444 // audio_frame.timestamp_ should be valid from now on.
445
446 // Compute elapsed time.
447 int64_t unwrap_timestamp =
448 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
449 audio_frame->elapsed_time_ms_ =
450 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
451 (GetRtpTimestampRateHz() / 1000);
452
453 {
Markus Handell62872802020-07-06 15:15:07 +0200454 MutexLock lock(&ts_stats_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200455 // Compute ntp time.
456 audio_frame->ntp_time_ms_ =
457 ntp_estimator_.Estimate(audio_frame->timestamp_);
Artem Titovb0ea6372021-07-26 11:47:07 +0200458 // `ntp_time_ms_` won't be valid until at least 2 RTCP SRs are received.
Niels Möller530ead42018-10-04 14:28:39 +0200459 if (audio_frame->ntp_time_ms_ > 0) {
Artem Titovb0ea6372021-07-26 11:47:07 +0200460 // Compute `capture_start_ntp_time_ms_` so that
461 // `capture_start_ntp_time_ms_` + `elapsed_time_ms_` == `ntp_time_ms_`
Niels Möller530ead42018-10-04 14:28:39 +0200462 capture_start_ntp_time_ms_ =
463 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
464 }
465 }
466 }
467
Artem Titovcfea2182021-08-10 01:22:31 +0200468 // Fill in local capture clock offset in `audio_frame->packet_infos_`.
Minyue Li63b30952021-05-19 14:38:25 +0200469 RtpPacketInfos::vector_type packet_infos;
470 for (auto& packet_info : audio_frame->packet_infos_) {
471 absl::optional<int64_t> local_capture_clock_offset;
472 if (packet_info.absolute_capture_time().has_value()) {
473 local_capture_clock_offset =
474 capture_clock_offset_updater_.AdjustEstimatedCaptureClockOffset(
475 packet_info.absolute_capture_time()
476 ->estimated_capture_clock_offset);
477 }
478 RtpPacketInfo new_packet_info(packet_info);
479 new_packet_info.set_local_capture_clock_offset(local_capture_clock_offset);
480 packet_infos.push_back(std::move(new_packet_info));
481 }
482 audio_frame->packet_infos_ = RtpPacketInfos(packet_infos);
483
Tommi3cc68ec2021-06-09 19:30:41 +0200484 ++audio_frame_interval_count_;
485 if (audio_frame_interval_count_ >= kHistogramReportingInterval) {
486 audio_frame_interval_count_ = 0;
487 worker_thread_->PostTask(ToQueuedTask(worker_safety_, [this]() {
488 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
489 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
490 acm_receiver_.TargetDelayMs());
491 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
492 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
493 jitter_buffer_delay + playout_delay_ms_);
494 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
495 jitter_buffer_delay);
496 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
497 playout_delay_ms_);
498 }));
499 }
Niels Möller530ead42018-10-04 14:28:39 +0200500
501 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
502 : AudioMixer::Source::AudioFrameInfo::kNormal;
503}
504
505int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100506 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200507 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200508 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
509 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200510}
511
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530512void ChannelReceive::SetSourceTracker(SourceTracker* source_tracker) {
513 source_tracker_ = source_tracker;
514}
515
Niels Möller530ead42018-10-04 14:28:39 +0200516ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100517 Clock* clock,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100518 NetEqFactory* neteq_factory,
Niels Möller530ead42018-10-04 14:28:39 +0200519 AudioDeviceModule* audio_device_module,
Niels Möllerae4237e2018-10-05 11:28:38 +0200520 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200521 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200522 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200523 uint32_t remote_ssrc,
524 size_t jitter_buffer_max_packets,
525 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100526 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100527 bool jitter_buffer_enable_rtx_handling,
Ivo Creusen2562cf02021-09-03 14:51:22 +0000528 bool enable_non_sender_rtt,
Niels Möller530ead42018-10-04 14:28:39 +0200529 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700530 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700531 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200532 const webrtc::CryptoOptions& crypto_options,
533 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer)
Tommie2e04642021-06-09 16:11:11 +0200534 : worker_thread_(TaskQueueBase::Current()),
535 event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100536 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200537 remote_ssrc_(remote_ssrc),
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100538 acm_receiver_(AcmConfig(neteq_factory,
539 decoder_factory,
Niels Möllered44f542019-07-30 15:15:59 +0200540 codec_pair_id,
541 jitter_buffer_max_packets,
542 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200543 _outputAudioLevel(),
Ranveer Aggarwaldea374a2021-01-23 12:27:19 +0530544 clock_(clock),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100545 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200546 playout_timestamp_rtp_(0),
547 playout_delay_ms_(0),
548 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
549 capture_start_rtp_time_stamp_(-1),
550 capture_start_ntp_time_ms_(-1),
Niels Möller530ead42018-10-04 14:28:39 +0200551 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200552 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700553 associated_send_channel_(nullptr),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700554 frame_decryptor_(frame_decryptor),
Minyue Lib506fee2020-02-11 13:04:02 +0100555 crypto_options_(crypto_options),
Minyue Li63b30952021-05-19 14:38:25 +0200556 absolute_capture_time_interpolator_(clock) {
Niels Möller530ead42018-10-04 14:28:39 +0200557 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200558
Tommi02df2eb2021-05-31 12:57:53 +0200559 network_thread_checker_.Detach();
560
Niels Möllered44f542019-07-30 15:15:59 +0200561 acm_receiver_.ResetInitialDelay();
562 acm_receiver_.SetMinimumDelay(0);
563 acm_receiver_.SetMaximumDelay(0);
564 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200565
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200566 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200567
568 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200569 RtpRtcpInterface::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100570 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200571 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100572 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200573 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200574 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200575 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200576 configuration.local_media_ssrc = local_ssrc;
Jakob Ivarssone54914a2021-07-01 11:16:05 +0200577 configuration.rtcp_packet_type_counter_observer = this;
Ivo Creusen2562cf02021-09-03 14:51:22 +0000578 configuration.non_sender_rtt_measurement = enable_non_sender_rtt;
Niels Möller530ead42018-10-04 14:28:39 +0200579
Marina Ciocea48623202020-04-01 10:19:44 +0200580 if (frame_transformer)
581 InitFrameTransformerDelegate(std::move(frame_transformer));
582
Niels Moller2accc7d2021-01-12 15:54:16 +0000583 rtp_rtcp_ = ModuleRtpRtcpImpl2::Create(configuration);
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200584 rtp_rtcp_->SetSendingMediaStatus(false);
585 rtp_rtcp_->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200586
Niels Möllerb6220d92019-08-29 13:47:09 +0200587 // Ensure that RTCP is enabled for the created channel.
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200588 rtp_rtcp_->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller530ead42018-10-04 14:28:39 +0200589}
590
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100591ChannelReceive::~ChannelReceive() {
Tommi6eda26c2021-06-09 13:46:28 +0200592 RTC_DCHECK_RUN_ON(&construction_thread_);
Niels Möller7d76a312018-10-26 12:57:07 +0200593
Marina Cioceaf4ee0362020-04-22 11:57:17 +0200594 // Resets the delegate's callback to ChannelReceive::OnReceivedPayloadData.
595 if (frame_transformer_delegate_)
596 frame_transformer_delegate_->Reset();
597
Niels Möller530ead42018-10-04 14:28:39 +0200598 StopPlayout();
Niels Möller530ead42018-10-04 14:28:39 +0200599}
600
601void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200602 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Markus Handell62872802020-07-06 15:15:07 +0200603 MutexLock lock(&callback_mutex_);
Niels Möller530ead42018-10-04 14:28:39 +0200604 audio_sink_ = sink;
605}
606
Niels Möller80c67622018-11-12 13:22:47 +0100607void ChannelReceive::StartPlayout() {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200608 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100609 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200610}
611
Niels Möller80c67622018-11-12 13:22:47 +0100612void ChannelReceive::StopPlayout() {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200613 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100614 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200615 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200616}
617
Jonas Olssona4d87372019-07-05 19:08:33 +0200618absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
619 const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200620 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möllered44f542019-07-30 15:15:59 +0200621 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200622}
623
Niels Möller530ead42018-10-04 14:28:39 +0200624void ChannelReceive::SetReceiveCodecs(
625 const std::map<int, SdpAudioFormat>& codecs) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200626 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200627 for (const auto& kv : codecs) {
628 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
629 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
630 }
Niels Möllered44f542019-07-30 15:15:59 +0200631 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200632}
633
Niels Möller530ead42018-10-04 14:28:39 +0200634void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
Tomas Gunnarsson209e2942021-04-01 22:03:05 +0200635 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200636 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
637 // network thread. Once that's done, the same applies to
638 // UpdatePlayoutTimestamp and
Niels Möller530ead42018-10-04 14:28:39 +0200639 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200640
Tommie2e04642021-06-09 16:11:11 +0200641 last_received_rtp_timestamp_ = packet.Timestamp();
642 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200643
644 // Store playout timestamp for the received RTP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200645 UpdatePlayoutTimestamp(false, now_ms);
Niels Möller530ead42018-10-04 14:28:39 +0200646
647 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
648 if (it == payload_type_frequencies_.end())
649 return;
650 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
651 RtpPacketReceived packet_copy(packet);
652 packet_copy.set_payload_type_frequency(it->second);
653
654 rtp_receive_statistics_->OnRtpPacket(packet_copy);
655
656 RTPHeader header;
657 packet_copy.GetHeader(&header);
658
Minyue Lib506fee2020-02-11 13:04:02 +0100659 // Interpolates absolute capture timestamp RTP header extension.
660 header.extension.absolute_capture_time =
Minyue Li63b30952021-05-19 14:38:25 +0200661 absolute_capture_time_interpolator_.OnReceivePacket(
662 AbsoluteCaptureTimeInterpolator::GetSource(header.ssrc,
663 header.arrOfCSRCs),
Minyue Lib506fee2020-02-11 13:04:02 +0100664 header.timestamp,
665 rtc::saturated_cast<uint32_t>(packet_copy.payload_type_frequency()),
666 header.extension.absolute_capture_time);
667
Marina Cioceafc23cc02020-04-02 12:10:03 +0200668 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
Niels Möller530ead42018-10-04 14:28:39 +0200669}
670
Niels Möllered44f542019-07-30 15:15:59 +0200671void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200672 size_t packet_length,
673 const RTPHeader& header) {
674 const uint8_t* payload = packet + header.headerLength;
Tommi6eda26c2021-06-09 13:46:28 +0200675 RTC_DCHECK_GE(packet_length, header.headerLength);
Niels Möller530ead42018-10-04 14:28:39 +0200676 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200677
Benjamin Wright84583f62018-10-04 14:22:34 -0700678 size_t payload_data_length = payload_length - header.paddingLength;
679
680 // E2EE Custom Audio Frame Decryption (This is optional).
681 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
682 rtc::Buffer decrypted_audio_payload;
683 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000684 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700685 cricket::MEDIA_TYPE_AUDIO, payload_length);
686 decrypted_audio_payload.SetSize(max_plaintext_size);
687
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000688 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
689 header.arrOfCSRCs + header.numCSRCs);
690 const FrameDecryptorInterface::Result decrypt_result =
691 frame_decryptor_->Decrypt(
692 cricket::MEDIA_TYPE_AUDIO, csrcs,
693 /*additional_data=*/nullptr,
694 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
695 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700696
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000697 if (decrypt_result.IsOk()) {
698 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
699 } else {
700 // Interpret failures as a silent frame.
701 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700702 }
703
Benjamin Wright84583f62018-10-04 14:22:34 -0700704 payload = decrypted_audio_payload.data();
705 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700706 } else if (crypto_options_.sframe.require_frame_encryption) {
707 RTC_DLOG(LS_ERROR)
708 << "FrameDecryptor required but not set, dropping packet";
709 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700710 }
711
Marina Cioceafc23cc02020-04-02 12:10:03 +0200712 rtc::ArrayView<const uint8_t> payload_data(payload, payload_data_length);
713 if (frame_transformer_delegate_) {
714 // Asynchronously transform the received payload. After the payload is
715 // transformed, the delegate will call OnReceivedPayloadData to handle it.
716 frame_transformer_delegate_->Transform(payload_data, header, remote_ssrc_);
717 } else {
718 OnReceivedPayloadData(payload_data, header);
719 }
Niels Möller530ead42018-10-04 14:28:39 +0200720}
721
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100722void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Tomas Gunnarsson209e2942021-04-01 22:03:05 +0200723 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200724 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
725 // network thread.
726
Niels Möller530ead42018-10-04 14:28:39 +0200727 // Store playout timestamp for the received RTCP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200728 UpdatePlayoutTimestamp(true, rtc::TimeMillis());
Niels Möller530ead42018-10-04 14:28:39 +0200729
730 // Deliver RTCP packet to RTP/RTCP module for parsing
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200731 rtp_rtcp_->IncomingRtcpPacket(data, length);
Niels Möller530ead42018-10-04 14:28:39 +0200732
733 int64_t rtt = GetRTT();
734 if (rtt == 0) {
735 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100736 return;
Niels Möller530ead42018-10-04 14:28:39 +0200737 }
738
Niels Möller530ead42018-10-04 14:28:39 +0200739 uint32_t ntp_secs = 0;
740 uint32_t ntp_frac = 0;
741 uint32_t rtp_timestamp = 0;
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100742 if (rtp_rtcp_->RemoteNTP(&ntp_secs, &ntp_frac,
743 /*rtcp_arrival_time_secs=*/nullptr,
744 /*rtcp_arrival_time_frac=*/nullptr,
745 &rtp_timestamp) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200746 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100747 return;
Niels Möller530ead42018-10-04 14:28:39 +0200748 }
749
750 {
Markus Handell62872802020-07-06 15:15:07 +0200751 MutexLock lock(&ts_stats_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200752 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
Minyue Li451a8af2021-02-24 09:12:50 +0100753 absl::optional<int64_t> remote_to_local_clock_offset_ms =
754 ntp_estimator_.EstimateRemoteToLocalClockOffsetMs();
755 if (remote_to_local_clock_offset_ms.has_value()) {
Minyue Li63b30952021-05-19 14:38:25 +0200756 capture_clock_offset_updater_.SetRemoteToLocalClockOffset(
Minyue Li451a8af2021-02-24 09:12:50 +0100757 Int64MsToQ32x32(*remote_to_local_clock_offset_ms));
758 }
Niels Möller530ead42018-10-04 14:28:39 +0200759 }
Niels Möller530ead42018-10-04 14:28:39 +0200760}
761
762int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200763 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200764 return _outputAudioLevel.LevelFullRange();
765}
766
767double ChannelReceive::GetTotalOutputEnergy() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200768 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200769 return _outputAudioLevel.TotalEnergy();
770}
771
772double ChannelReceive::GetTotalOutputDuration() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200773 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200774 return _outputAudioLevel.TotalDuration();
775}
776
777void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200778 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Markus Handell62872802020-07-06 15:15:07 +0200779 MutexLock lock(&volume_settings_mutex_);
Niels Möller530ead42018-10-04 14:28:39 +0200780 _outputGain = scaling;
781}
782
Niels Möller530ead42018-10-04 14:28:39 +0200783void ChannelReceive::RegisterReceiverCongestionControlObjects(
784 PacketRouter* packet_router) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200785 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200786 RTC_DCHECK(packet_router);
787 RTC_DCHECK(!packet_router_);
788 constexpr bool remb_candidate = false;
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200789 packet_router->AddReceiveRtpModule(rtp_rtcp_.get(), remb_candidate);
Niels Möller530ead42018-10-04 14:28:39 +0200790 packet_router_ = packet_router;
791}
792
793void ChannelReceive::ResetReceiverCongestionControlObjects() {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200794 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200795 RTC_DCHECK(packet_router_);
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200796 packet_router_->RemoveReceiveRtpModule(rtp_rtcp_.get());
Niels Möller530ead42018-10-04 14:28:39 +0200797 packet_router_ = nullptr;
798}
799
Niels Möller349ade32018-11-16 09:50:42 +0100800CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200801 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller80c67622018-11-12 13:22:47 +0100802 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200803
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100804 // The jitter statistics is updated for each received RTP packet and is based
805 // on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200806 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200807 StreamStatistician* statistician =
808 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
809 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200810 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200811 }
812
Niels Möllerd77cc242019-08-22 09:40:25 +0200813 stats.cumulativeLost = rtp_stats.packets_lost;
814 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200815
Niels Möller530ead42018-10-04 14:28:39 +0200816 stats.rttMs = GetRTT();
817
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100818 // Data counters.
Niels Möller530ead42018-10-04 14:28:39 +0200819 if (statistician) {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200820 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
821
822 stats.header_and_padding_bytes_rcvd =
823 rtp_stats.packet_counter.header_bytes +
824 rtp_stats.packet_counter.padding_bytes;
Niels Möllerd77cc242019-08-22 09:40:25 +0200825 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200826 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200827 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200828 } else {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200829 stats.payload_bytes_rcvd = 0;
830 stats.header_and_padding_bytes_rcvd = 0;
Henrik Boström01738c62019-04-15 17:32:00 +0200831 stats.packetsReceived = 0;
832 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200833 }
834
Jakob Ivarssone54914a2021-07-01 11:16:05 +0200835 {
836 MutexLock lock(&rtcp_counter_mutex_);
837 stats.nacks_sent = rtcp_packet_type_counter_.nack_packets;
838 }
839
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100840 // Timestamps.
Niels Möller530ead42018-10-04 14:28:39 +0200841 {
Markus Handell62872802020-07-06 15:15:07 +0200842 MutexLock lock(&ts_stats_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200843 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
844 }
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100845
846 absl::optional<RtpRtcpInterface::SenderReportStats> rtcp_sr_stats =
847 rtp_rtcp_->GetSenderReportStats();
848 if (rtcp_sr_stats.has_value()) {
849 stats.last_sender_report_timestamp_ms =
Nico Grunbaum7eac6ca2022-01-24 13:49:58 -0800850 rtcp_sr_stats->last_arrival_timestamp.ToMs() -
851 rtc::kNtpJan1970Millisecs;
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100852 stats.last_sender_report_remote_timestamp_ms =
Nico Grunbaum7eac6ca2022-01-24 13:49:58 -0800853 rtcp_sr_stats->last_remote_timestamp.ToMs() - rtc::kNtpJan1970Millisecs;
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100854 stats.sender_reports_packets_sent = rtcp_sr_stats->packets_sent;
855 stats.sender_reports_bytes_sent = rtcp_sr_stats->bytes_sent;
856 stats.sender_reports_reports_count = rtcp_sr_stats->reports_count;
857 }
858
Ivo Creusen2562cf02021-09-03 14:51:22 +0000859 absl::optional<RtpRtcpInterface::NonSenderRttStats> non_sender_rtt_stats =
860 rtp_rtcp_->GetNonSenderRttStats();
861 if (non_sender_rtt_stats.has_value()) {
862 stats.round_trip_time = non_sender_rtt_stats->round_trip_time;
863 stats.round_trip_time_measurements =
864 non_sender_rtt_stats->round_trip_time_measurements;
865 stats.total_round_trip_time = non_sender_rtt_stats->total_round_trip_time;
866 }
867
Niels Möller80c67622018-11-12 13:22:47 +0100868 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200869}
870
Niels Möller349ade32018-11-16 09:50:42 +0100871void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200872 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200873 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100874 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200875 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
876 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100877 } else {
878 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200879 kDefaultMaxReorderingThreshold);
880 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100881 }
Niels Möller530ead42018-10-04 14:28:39 +0200882}
883
Ivo Creusen2562cf02021-09-03 14:51:22 +0000884void ChannelReceive::SetNonSenderRttMeasurement(bool enabled) {
885 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
886 rtp_rtcp_->SetNonSenderRttMeasurement(enabled);
887}
888
Niels Möller530ead42018-10-04 14:28:39 +0200889// Called when we are missing one or more packets.
890int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
891 int length) {
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +0200892 return rtp_rtcp_->SendNACK(sequence_numbers, length);
Niels Möller530ead42018-10-04 14:28:39 +0200893}
894
Jakob Ivarssone54914a2021-07-01 11:16:05 +0200895void ChannelReceive::RtcpPacketTypesCounterUpdated(
896 uint32_t ssrc,
897 const RtcpPacketTypeCounter& packet_counter) {
898 if (ssrc != remote_ssrc_) {
899 return;
900 }
901 MutexLock lock(&rtcp_counter_mutex_);
902 rtcp_packet_type_counter_ = packet_counter;
903}
904
Niels Möllerdced9f62018-11-19 10:27:07 +0100905void ChannelReceive::SetAssociatedSendChannel(
906 const ChannelSendInterface* channel) {
Tommi02df2eb2021-05-31 12:57:53 +0200907 RTC_DCHECK_RUN_ON(&network_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200908 associated_send_channel_ = channel;
909}
910
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200911void ChannelReceive::SetDepacketizerToDecoderFrameTransformer(
912 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200913 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Marina Ciocea48623202020-04-01 10:19:44 +0200914 // Depending on when the channel is created, the transformer might be set
915 // twice. Don't replace the delegate if it was already initialized.
Tommi6eda26c2021-06-09 13:46:28 +0200916 if (!frame_transformer || frame_transformer_delegate_) {
Artem Titovd3251962021-11-15 16:57:07 +0100917 RTC_DCHECK_NOTREACHED() << "Not setting the transformer?";
Marina Ciocea48623202020-04-01 10:19:44 +0200918 return;
Tommi6eda26c2021-06-09 13:46:28 +0200919 }
920
Marina Ciocea48623202020-04-01 10:19:44 +0200921 InitFrameTransformerDelegate(std::move(frame_transformer));
Marina Ciocea3e9af7f2020-04-01 07:46:16 +0200922}
923
Tommie0972822021-06-14 08:11:10 +0200924void ChannelReceive::SetFrameDecryptor(
925 rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
926 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
927 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
928 frame_decryptor_ = std::move(frame_decryptor);
929}
930
Tommi08be9ba2021-06-15 23:01:57 +0200931void ChannelReceive::OnLocalSsrcChange(uint32_t local_ssrc) {
932 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
933 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
934 rtp_rtcp_->SetLocalSsrc(local_ssrc);
935}
936
937uint32_t ChannelReceive::GetLocalSsrc() const {
938 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
939 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
940 return rtp_rtcp_->local_media_ssrc();
941}
942
Niels Möller6b4d9622020-09-14 10:47:50 +0200943NetworkStatistics ChannelReceive::GetNetworkStatistics(
944 bool get_and_clear_legacy_stats) const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200945 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller80c67622018-11-12 13:22:47 +0100946 NetworkStatistics stats;
Niels Möller6b4d9622020-09-14 10:47:50 +0200947 acm_receiver_.GetNetworkStatistics(&stats, get_and_clear_legacy_stats);
Niels Möller80c67622018-11-12 13:22:47 +0100948 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200949}
950
Niels Möller80c67622018-11-12 13:22:47 +0100951AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200952 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller80c67622018-11-12 13:22:47 +0100953 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200954 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100955 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200956}
957
958uint32_t ChannelReceive::GetDelayEstimate() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200959 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200960 // Return the current jitter buffer delay + playout delay.
Tommie2e04642021-06-09 16:11:11 +0200961 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200962}
963
Ivo Creusenbef7b052020-09-08 16:30:25 +0200964bool ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +0200965 // TODO(bugs.webrtc.org/11993): This should run on the network thread.
966 // We get here via RtpStreamsSynchronizer. Once that's done, many (all?) of
967 // these locks aren't needed.
968 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller349ade32018-11-16 09:50:42 +0100969 // Limit to range accepted by both VoE and ACM, so we're at least getting as
970 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100971 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
972 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200973 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200974 RTC_DLOG(LS_ERROR)
975 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Ivo Creusenbef7b052020-09-08 16:30:25 +0200976 return false;
Niels Möller530ead42018-10-04 14:28:39 +0200977 }
Ivo Creusenbef7b052020-09-08 16:30:25 +0200978 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200979}
980
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200981bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
982 int64_t* time_ms) const {
Tommie2e04642021-06-09 16:11:11 +0200983 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
984 if (!playout_timestamp_rtp_time_ms_)
985 return false;
986 *rtp_timestamp = playout_timestamp_rtp_;
987 *time_ms = playout_timestamp_rtp_time_ms_.value();
988 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200989}
990
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200991void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
992 int64_t time_ms) {
Tommie2e04642021-06-09 16:11:11 +0200993 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200994 playout_timestamp_ntp_ = ntp_timestamp_ms;
995 playout_timestamp_ntp_time_ms_ = time_ms;
996}
997
998absl::optional<int64_t>
999ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001000 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +02001001 if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_)
1002 return absl::nullopt;
1003
1004 int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_;
1005 return *playout_timestamp_ntp_ + elapsed_ms;
1006}
1007
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +01001008bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +02001009 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +01001010}
1011
1012int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +02001013 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +01001014}
1015
Niels Möller530ead42018-10-04 14:28:39 +02001016absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001017 // TODO(bugs.webrtc.org/11993): This should run on the network thread.
1018 // We get here via RtpStreamsSynchronizer. Once that's done, many of
1019 // these locks aren't needed.
1020 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +02001021 Syncable::Info info;
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +02001022 if (rtp_rtcp_->RemoteNTP(&info.capture_time_ntp_secs,
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +01001023 &info.capture_time_ntp_frac,
1024 /*rtcp_arrival_time_secs=*/nullptr,
1025 /*rtcp_arrival_time_frac=*/nullptr,
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +02001026 &info.capture_time_source_clock) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +02001027 return absl::nullopt;
1028 }
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001029
Tommie2e04642021-06-09 16:11:11 +02001030 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
1031 return absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +02001032 }
Tommie2e04642021-06-09 16:11:11 +02001033 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
1034 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001035
1036 int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Tommie2e04642021-06-09 16:11:11 +02001037 info.current_delay_ms = jitter_buffer_delay + playout_delay_ms_;
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001038
Niels Möller530ead42018-10-04 14:28:39 +02001039 return info;
1040}
1041
Tommie2e04642021-06-09 16:11:11 +02001042// RTC_RUN_ON(worker_thread_checker_)
Åsa Perssonfcf79cc2019-10-22 15:23:44 +02001043void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) {
Tomas Gunnarsson0f030fd2021-04-01 20:12:04 +02001044 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
1045 // network thread. Once that's done, we won't need video_sync_lock_.
1046
Niels Möllered44f542019-07-30 15:15:59 +02001047 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +02001048
1049 if (!jitter_buffer_playout_timestamp_) {
1050 // This can happen if this channel has not received any RTP packets. In
1051 // this case, NetEq is not capable of computing a playout timestamp.
1052 return;
1053 }
1054
1055 uint16_t delay_ms = 0;
1056 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
1057 RTC_DLOG(LS_WARNING)
1058 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
Jonas Olssonb2b20312020-01-14 12:11:31 +01001059 " playout delay from the ADM";
Niels Möller530ead42018-10-04 14:28:39 +02001060 return;
1061 }
1062
1063 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1064 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
1065
1066 // Remove the playout delay.
1067 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
1068
Tommie2e04642021-06-09 16:11:11 +02001069 if (!rtcp && playout_timestamp != playout_timestamp_rtp_) {
1070 playout_timestamp_rtp_ = playout_timestamp;
1071 playout_timestamp_rtp_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +02001072 }
Tommie2e04642021-06-09 16:11:11 +02001073 playout_delay_ms_ = delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +02001074}
1075
1076int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +02001077 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +02001078 // Default to the playout frequency if we've not gotten any packets yet.
1079 // TODO(ossu): Zero clockrate can only happen if we've added an external
1080 // decoder for a format we don't support internally. Remove once that way of
1081 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +02001082 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
1083 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
1084 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +01001085 return (decoder && decoder->second.clockrate_hz != 0)
1086 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +02001087 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +02001088}
1089
1090int64_t ChannelReceive::GetRTT() const {
Tommi02df2eb2021-05-31 12:57:53 +02001091 RTC_DCHECK_RUN_ON(&network_thread_checker_);
Danil Chapovalov5eda59c2021-02-18 20:53:28 +01001092 std::vector<ReportBlockData> report_blocks =
1093 rtp_rtcp_->GetLatestReportBlockData();
Niels Möller530ead42018-10-04 14:28:39 +02001094
Niels Möller530ead42018-10-04 14:28:39 +02001095 if (report_blocks.empty()) {
Tomas Gunnarsson209e2942021-04-01 22:03:05 +02001096 // Try fall back on an RTT from an associated channel.
Niels Möller530ead42018-10-04 14:28:39 +02001097 if (!associated_send_channel_) {
1098 return 0;
1099 }
1100 return associated_send_channel_->GetRTT();
1101 }
1102
Niels Möllerfd1a2fb2018-10-31 15:25:26 +01001103 // TODO(nisse): This method computes RTT based on sender reports, even though
1104 // a receive stream is not supposed to do that.
Danil Chapovalov5eda59c2021-02-18 20:53:28 +01001105 for (const ReportBlockData& data : report_blocks) {
1106 if (data.report_block().sender_ssrc == remote_ssrc_) {
1107 return data.last_rtt_ms();
1108 }
Niels Möller530ead42018-10-04 14:28:39 +02001109 }
Danil Chapovalov5eda59c2021-02-18 20:53:28 +01001110 return 0;
Niels Möller530ead42018-10-04 14:28:39 +02001111}
1112
Niels Möller349ade32018-11-16 09:50:42 +01001113} // namespace
1114
1115std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +01001116 Clock* clock,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +01001117 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +01001118 AudioDeviceModule* audio_device_module,
Niels Möller349ade32018-11-16 09:50:42 +01001119 Transport* rtcp_send_transport,
1120 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +02001121 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +01001122 uint32_t remote_ssrc,
1123 size_t jitter_buffer_max_packets,
1124 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001125 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001126 bool jitter_buffer_enable_rtx_handling,
Ivo Creusen2562cf02021-09-03 14:51:22 +00001127 bool enable_non_sender_rtt,
Niels Möller349ade32018-11-16 09:50:42 +01001128 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
1129 absl::optional<AudioCodecPairId> codec_pair_id,
1130 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Marina Ciocea3e9af7f2020-04-01 07:46:16 +02001131 const webrtc::CryptoOptions& crypto_options,
1132 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001133 return std::make_unique<ChannelReceive>(
Markus Handelleb61b7f2021-06-22 10:46:48 +02001134 clock, neteq_factory, audio_device_module, rtcp_send_transport,
1135 rtc_event_log, local_ssrc, remote_ssrc, jitter_buffer_max_packets,
1136 jitter_buffer_fast_playout, jitter_buffer_min_delay_ms,
Ivo Creusen2562cf02021-09-03 14:51:22 +00001137 jitter_buffer_enable_rtx_handling, enable_non_sender_rtt, decoder_factory,
1138 codec_pair_id, std::move(frame_decryptor), crypto_options,
1139 std::move(frame_transformer));
Niels Möller349ade32018-11-16 09:50:42 +01001140}
1141
Niels Möller530ead42018-10-04 14:28:39 +02001142} // namespace voe
1143} // namespace webrtc