blob: dfc849394f43a434e5a2e4e8357f23422d9603d4 [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
Jerome Humbert39bab5a2019-10-28 18:12:51 +000013#include <assert.h>
14
Niels Möller530ead42018-10-04 14:28:39 +020015#include <algorithm>
16#include <map>
17#include <memory>
18#include <string>
19#include <utility>
20#include <vector>
21
Niels Möllera8370302019-09-02 15:16:49 +020022#include "api/crypto/frame_decryptor_interface.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020023#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller349ade32018-11-16 09:50:42 +010024#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020025#include "audio/channel_send.h"
26#include "audio/utility/audio_frame_operations.h"
27#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möllered44f542019-07-30 15:15:59 +020028#include "modules/audio_coding/acm2/acm_receiver.h"
Niels Möller530ead42018-10-04 14:28:39 +020029#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
30#include "modules/audio_device/include/audio_device.h"
31#include "modules/pacing/packet_router.h"
32#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010033#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
34#include "modules/rtp_rtcp/include/rtp_rtcp.h"
Minyue Lib506fee2020-02-11 13:04:02 +010035#include "modules/rtp_rtcp/source/absolute_capture_time_receiver.h"
Yves Gerey988cc082018-10-23 12:03:01 +020036#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020037#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010038#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#include "modules/utility/include/process_thread.h"
40#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020042#include "rtc_base/format_macros.h"
43#include "rtc_base/location.h"
44#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010045#include "rtc_base/numerics/safe_minmax.h"
46#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020047#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020049#include "system_wrappers/include/metrics.h"
50
51namespace webrtc {
52namespace voe {
53
54namespace {
55
56constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020057
58// Video Sync.
59constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
60constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
61
Niels Möllered44f542019-07-30 15:15:59 +020062AudioCodingModule::Config AcmConfig(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010063 NetEqFactory* neteq_factory,
Niels Möllered44f542019-07-30 15:15:59 +020064 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
65 absl::optional<AudioCodecPairId> codec_pair_id,
66 size_t jitter_buffer_max_packets,
67 bool jitter_buffer_fast_playout) {
68 AudioCodingModule::Config acm_config;
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010069 acm_config.neteq_factory = neteq_factory;
Niels Möllered44f542019-07-30 15:15:59 +020070 acm_config.decoder_factory = decoder_factory;
71 acm_config.neteq_config.codec_pair_id = codec_pair_id;
72 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
73 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
74 acm_config.neteq_config.enable_muted_state = true;
75
76 return acm_config;
77}
78
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -080079class ChannelReceive : public ChannelReceiveInterface {
Niels Möller349ade32018-11-16 09:50:42 +010080 public:
81 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010082 ChannelReceive(Clock* clock,
83 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010084 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +010085 AudioDeviceModule* audio_device_module,
Niels Möller349ade32018-11-16 09:50:42 +010086 Transport* rtcp_send_transport,
87 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +020088 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +010089 uint32_t remote_ssrc,
90 size_t jitter_buffer_max_packets,
91 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010092 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +010093 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +010094 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
95 absl::optional<AudioCodecPairId> codec_pair_id,
96 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
97 const webrtc::CryptoOptions& crypto_options);
98 ~ChannelReceive() override;
99
100 void SetSink(AudioSinkInterface* sink) override;
101
102 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
103
104 // API methods
105
106 void StartPlayout() override;
107 void StopPlayout() override;
108
109 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000110 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
111 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100112
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100113 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100114
115 // RtpPacketSinkInterface.
116 void OnRtpPacket(const RtpPacketReceived& packet) override;
117
118 // Muting, Volume and Level.
119 void SetChannelOutputVolumeScaling(float scaling) override;
120 int GetSpeechOutputLevelFullRange() const override;
121 // See description of "totalAudioEnergy" in the WebRTC stats spec:
122 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
123 double GetTotalOutputEnergy() const override;
124 double GetTotalOutputDuration() const override;
125
126 // Stats.
127 NetworkStatistics GetNetworkStatistics() const override;
128 AudioDecodingCallStats GetDecodingCallStatistics() const override;
129
130 // Audio+Video Sync.
131 uint32_t GetDelayEstimate() const override;
132 void SetMinimumPlayoutDelay(int delayMs) override;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200133 bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
134 int64_t* time_ms) const override;
135 void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
136 int64_t time_ms) override;
137 absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs(
138 int64_t now_ms) const override;
Niels Möller349ade32018-11-16 09:50:42 +0100139
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100140 // Audio quality.
141 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
142 int GetBaseMinimumPlayoutDelayMs() const override;
143
Niels Möller349ade32018-11-16 09:50:42 +0100144 // Produces the transport-related timestamps; current_delay_ms is left unset.
145 absl::optional<Syncable::Info> GetSyncInfo() const override;
146
Niels Möller349ade32018-11-16 09:50:42 +0100147 void RegisterReceiverCongestionControlObjects(
148 PacketRouter* packet_router) override;
149 void ResetReceiverCongestionControlObjects() override;
150
151 CallReceiveStatistics GetRTCPStatistics() const override;
152 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
153
154 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
155 int sample_rate_hz,
156 AudioFrame* audio_frame) override;
157
158 int PreferredSampleRate() const override;
159
160 // Associate to a send channel.
161 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100162 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100163
Niels Möller349ade32018-11-16 09:50:42 +0100164 private:
Niels Möllered44f542019-07-30 15:15:59 +0200165 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100166 size_t packet_length,
167 const RTPHeader& header);
168 int ResendPackets(const uint16_t* sequence_numbers, int length);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200169 void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms);
Niels Möller349ade32018-11-16 09:50:42 +0100170
171 int GetRtpTimestampRateHz() const;
172 int64_t GetRTT() const;
173
Niels Möllered44f542019-07-30 15:15:59 +0200174 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
175 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100176
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100177 bool Playing() const {
178 rtc::CritScope lock(&playing_lock_);
179 return playing_;
180 }
181
Niels Möller349ade32018-11-16 09:50:42 +0100182 // Thread checkers document and lock usage of some methods to specific threads
183 // we know about. The goal is to eventually split up voe::ChannelReceive into
184 // parts with single-threaded semantics, and thereby reduce the need for
185 // locks.
186 rtc::ThreadChecker worker_thread_checker_;
187 rtc::ThreadChecker module_process_thread_checker_;
188 // Methods accessed from audio and video threads are checked for sequential-
189 // only access. We don't necessarily own and control these threads, so thread
190 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
191 // audio thread to another, but access is still sequential.
192 rtc::RaceChecker audio_thread_race_checker_;
193 rtc::RaceChecker video_capture_thread_race_checker_;
194 rtc::CriticalSection _callbackCritSect;
195 rtc::CriticalSection volume_settings_critsect_;
196
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100197 rtc::CriticalSection playing_lock_;
198 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100199
200 RtcEventLog* const event_log_;
201
202 // Indexed by payload type.
203 std::map<uint8_t, int> payload_type_frequencies_;
204
205 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
206 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
207 const uint32_t remote_ssrc_;
208
Chen Xing054e3bb2019-08-02 10:29:26 +0000209 // Info for GetSyncInfo is updated on network or worker thread, and queried on
210 // the worker thread.
211 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100212 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000213 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100214 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000215 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100216
Niels Möllered44f542019-07-30 15:15:59 +0200217 // The AcmReceiver is thread safe, using its own lock.
218 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100219 AudioSinkInterface* audio_sink_ = nullptr;
220 AudioLevel _outputAudioLevel;
221
222 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
223
224 // Timestamp of the audio pulled from NetEq.
225 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
226
227 rtc::CriticalSection video_sync_lock_;
228 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200229 absl::optional<int64_t> playout_timestamp_rtp_time_ms_
230 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100231 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200232 absl::optional<int64_t> playout_timestamp_ntp_
233 RTC_GUARDED_BY(video_sync_lock_);
234 absl::optional<int64_t> playout_timestamp_ntp_time_ms_
235 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100236
237 rtc::CriticalSection ts_stats_lock_;
238
239 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
240 // The rtp timestamp of the first played out audio frame.
241 int64_t capture_start_rtp_time_stamp_;
242 // The capture ntp time (in local timebase) of the first played out audio
243 // frame.
244 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
245
246 // uses
247 ProcessThread* _moduleProcessThreadPtr;
248 AudioDeviceModule* _audioDeviceModulePtr;
249 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
250
251 // An associated send channel.
252 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100253 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100254 RTC_GUARDED_BY(assoc_send_channel_lock_);
255
256 PacketRouter* packet_router_ = nullptr;
257
258 rtc::ThreadChecker construction_thread_;
259
Niels Möller349ade32018-11-16 09:50:42 +0100260 // E2EE Audio Frame Decryption
261 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
262 webrtc::CryptoOptions crypto_options_;
Minyue Lib506fee2020-02-11 13:04:02 +0100263
264 webrtc::AbsoluteCaptureTimeReceiver absolute_capture_time_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100265};
Niels Möller530ead42018-10-04 14:28:39 +0200266
Niels Möllered44f542019-07-30 15:15:59 +0200267void ChannelReceive::OnReceivedPayloadData(
268 rtc::ArrayView<const uint8_t> payload,
269 const RTPHeader& rtpHeader) {
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100270 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200271 // Avoid inserting into NetEQ when we are not playing. Count the
272 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200273 return;
Niels Möller530ead42018-10-04 14:28:39 +0200274 }
275
276 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200277 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200278 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
279 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200280 return;
Niels Möller530ead42018-10-04 14:28:39 +0200281 }
282
283 int64_t round_trip_time = 0;
284 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
285
Niels Möllered44f542019-07-30 15:15:59 +0200286 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200287 if (!nack_list.empty()) {
288 // Can't use nack_list.data() since it's not supported by all
289 // compilers.
290 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
291 }
Niels Möller530ead42018-10-04 14:28:39 +0200292}
293
294AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
295 int sample_rate_hz,
296 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100297 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200298 audio_frame->sample_rate_hz_ = sample_rate_hz;
299
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200300 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100301
Niels Möller530ead42018-10-04 14:28:39 +0200302 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
303 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200304 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
305 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200306 RTC_DLOG(LS_ERROR)
307 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
308 // In all likelihood, the audio in this frame is garbage. We return an
309 // error so that the audio mixer module doesn't add it to the mix. As
310 // a result, it won't be played out and the actions skipped here are
311 // irrelevant.
312 return AudioMixer::Source::AudioFrameInfo::kError;
313 }
314
315 if (muted) {
316 // TODO(henrik.lundin): We should be able to do better than this. But we
317 // will have to go through all the cases below where the audio samples may
318 // be used, and handle the muted case in some way.
319 AudioFrameOperations::Mute(audio_frame);
320 }
321
322 {
323 // Pass the audio buffers to an optional sink callback, before applying
324 // scaling/panning, as that applies to the mix operation.
325 // External recipients of the audio (e.g. via AudioTrack), will do their
326 // own mixing/dynamic processing.
327 rtc::CritScope cs(&_callbackCritSect);
328 if (audio_sink_) {
329 AudioSinkInterface::Data data(
330 audio_frame->data(), audio_frame->samples_per_channel_,
331 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
332 audio_frame->timestamp_);
333 audio_sink_->OnData(data);
334 }
335 }
336
337 float output_gain = 1.0f;
338 {
339 rtc::CritScope cs(&volume_settings_critsect_);
340 output_gain = _outputGain;
341 }
342
343 // Output volume scaling
344 if (output_gain < 0.99f || output_gain > 1.01f) {
345 // TODO(solenberg): Combine with mute state - this can cause clicks!
346 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
347 }
348
349 // Measure audio level (0-9)
350 // TODO(henrik.lundin) Use the |muted| information here too.
351 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
352 // https://crbug.com/webrtc/7517).
353 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
354
355 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
356 // The first frame with a valid rtp timestamp.
357 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
358 }
359
360 if (capture_start_rtp_time_stamp_ >= 0) {
361 // audio_frame.timestamp_ should be valid from now on.
362
363 // Compute elapsed time.
364 int64_t unwrap_timestamp =
365 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
366 audio_frame->elapsed_time_ms_ =
367 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
368 (GetRtpTimestampRateHz() / 1000);
369
370 {
371 rtc::CritScope lock(&ts_stats_lock_);
372 // Compute ntp time.
373 audio_frame->ntp_time_ms_ =
374 ntp_estimator_.Estimate(audio_frame->timestamp_);
375 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
376 if (audio_frame->ntp_time_ms_ > 0) {
377 // Compute |capture_start_ntp_time_ms_| so that
378 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
379 capture_start_ntp_time_ms_ =
380 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
381 }
382 }
383 }
384
385 {
386 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200387 acm_receiver_.TargetDelayMs());
388 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200389 rtc::CritScope lock(&video_sync_lock_);
390 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
391 jitter_buffer_delay + playout_delay_ms_);
392 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
393 jitter_buffer_delay);
394 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
395 playout_delay_ms_);
396 }
397
398 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
399 : AudioMixer::Source::AudioFrameInfo::kNormal;
400}
401
402int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100403 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200404 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200405 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
406 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200407}
408
409ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100410 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200411 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100412 NetEqFactory* neteq_factory,
Niels Möller530ead42018-10-04 14:28:39 +0200413 AudioDeviceModule* audio_device_module,
Niels Möllerae4237e2018-10-05 11:28:38 +0200414 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200415 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200416 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200417 uint32_t remote_ssrc,
418 size_t jitter_buffer_max_packets,
419 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100420 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100421 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200422 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700423 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700424 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700425 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200426 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100427 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200428 remote_ssrc_(remote_ssrc),
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100429 acm_receiver_(AcmConfig(neteq_factory,
430 decoder_factory,
Niels Möllered44f542019-07-30 15:15:59 +0200431 codec_pair_id,
432 jitter_buffer_max_packets,
433 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200434 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100435 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200436 playout_timestamp_rtp_(0),
437 playout_delay_ms_(0),
438 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
439 capture_start_rtp_time_stamp_(-1),
440 capture_start_ntp_time_ms_(-1),
441 _moduleProcessThreadPtr(module_process_thread),
442 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200443 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700444 associated_send_channel_(nullptr),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700445 frame_decryptor_(frame_decryptor),
Minyue Lib506fee2020-02-11 13:04:02 +0100446 crypto_options_(crypto_options),
447 absolute_capture_time_receiver_(clock) {
Niels Möller349ade32018-11-16 09:50:42 +0100448 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200449 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100450
Niels Möller530ead42018-10-04 14:28:39 +0200451 RTC_DCHECK(module_process_thread);
452 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200453
454 acm_receiver_.ResetInitialDelay();
455 acm_receiver_.SetMinimumDelay(0);
456 acm_receiver_.SetMaximumDelay(0);
457 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200458
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200459 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200460
461 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
462 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100463 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200464 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100465 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200466 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200467 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200468 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200469 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200470
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100471 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200472 _rtpRtcpModule->SetSendingMediaStatus(false);
473 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200474
Niels Möller530ead42018-10-04 14:28:39 +0200475 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
476
Niels Möllerb6220d92019-08-29 13:47:09 +0200477 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200478 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
479}
480
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100481ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200482 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200483
Niels Möller530ead42018-10-04 14:28:39 +0200484 StopPlayout();
485
Niels Möller530ead42018-10-04 14:28:39 +0200486 if (_moduleProcessThreadPtr)
487 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200488}
489
490void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200491 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200492 rtc::CritScope cs(&_callbackCritSect);
493 audio_sink_ = sink;
494}
495
Niels Möller80c67622018-11-12 13:22:47 +0100496void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200497 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100498 rtc::CritScope lock(&playing_lock_);
499 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200500}
501
Niels Möller80c67622018-11-12 13:22:47 +0100502void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200503 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100504 rtc::CritScope lock(&playing_lock_);
505 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200506 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200507}
508
Jonas Olssona4d87372019-07-05 19:08:33 +0200509absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
510 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200511 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200512 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200513}
514
Niels Möller530ead42018-10-04 14:28:39 +0200515void ChannelReceive::SetReceiveCodecs(
516 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200517 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200518 for (const auto& kv : codecs) {
519 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
520 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
521 }
Niels Möllered44f542019-07-30 15:15:59 +0200522 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200523}
524
Niels Möller349ade32018-11-16 09:50:42 +0100525// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200526void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
527 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200528
529 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000530 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200531 last_received_rtp_timestamp_ = packet.Timestamp();
532 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200533 }
534
535 // Store playout timestamp for the received RTP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200536 UpdatePlayoutTimestamp(false, now_ms);
Niels Möller530ead42018-10-04 14:28:39 +0200537
538 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
539 if (it == payload_type_frequencies_.end())
540 return;
541 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
542 RtpPacketReceived packet_copy(packet);
543 packet_copy.set_payload_type_frequency(it->second);
544
545 rtp_receive_statistics_->OnRtpPacket(packet_copy);
546
547 RTPHeader header;
548 packet_copy.GetHeader(&header);
549
Minyue Lib506fee2020-02-11 13:04:02 +0100550 // Interpolates absolute capture timestamp RTP header extension.
551 header.extension.absolute_capture_time =
552 absolute_capture_time_receiver_.OnReceivePacket(
553 AbsoluteCaptureTimeReceiver::GetSource(header.ssrc,
554 header.arrOfCSRCs),
555 header.timestamp,
556 rtc::saturated_cast<uint32_t>(packet_copy.payload_type_frequency()),
557 header.extension.absolute_capture_time);
558
Niels Möller530ead42018-10-04 14:28:39 +0200559 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
560}
561
Niels Möllered44f542019-07-30 15:15:59 +0200562void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200563 size_t packet_length,
564 const RTPHeader& header) {
565 const uint8_t* payload = packet + header.headerLength;
566 assert(packet_length >= header.headerLength);
567 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200568
Benjamin Wright84583f62018-10-04 14:22:34 -0700569 size_t payload_data_length = payload_length - header.paddingLength;
570
571 // E2EE Custom Audio Frame Decryption (This is optional).
572 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
573 rtc::Buffer decrypted_audio_payload;
574 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000575 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700576 cricket::MEDIA_TYPE_AUDIO, payload_length);
577 decrypted_audio_payload.SetSize(max_plaintext_size);
578
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000579 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
580 header.arrOfCSRCs + header.numCSRCs);
581 const FrameDecryptorInterface::Result decrypt_result =
582 frame_decryptor_->Decrypt(
583 cricket::MEDIA_TYPE_AUDIO, csrcs,
584 /*additional_data=*/nullptr,
585 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
586 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700587
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000588 if (decrypt_result.IsOk()) {
589 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
590 } else {
591 // Interpret failures as a silent frame.
592 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700593 }
594
Benjamin Wright84583f62018-10-04 14:22:34 -0700595 payload = decrypted_audio_payload.data();
596 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700597 } else if (crypto_options_.sframe.require_frame_encryption) {
598 RTC_DLOG(LS_ERROR)
599 << "FrameDecryptor required but not set, dropping packet";
600 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700601 }
602
Niels Möllered44f542019-07-30 15:15:59 +0200603 OnReceivedPayloadData(
604 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200605}
606
Niels Möller349ade32018-11-16 09:50:42 +0100607// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100608void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200609 // Store playout timestamp for the received RTCP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200610 UpdatePlayoutTimestamp(true, rtc::TimeMillis());
Niels Möller530ead42018-10-04 14:28:39 +0200611
612 // Deliver RTCP packet to RTP/RTCP module for parsing
613 _rtpRtcpModule->IncomingRtcpPacket(data, length);
614
615 int64_t rtt = GetRTT();
616 if (rtt == 0) {
617 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100618 return;
Niels Möller530ead42018-10-04 14:28:39 +0200619 }
620
Niels Möller530ead42018-10-04 14:28:39 +0200621 uint32_t ntp_secs = 0;
622 uint32_t ntp_frac = 0;
623 uint32_t rtp_timestamp = 0;
624 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
625 &rtp_timestamp)) {
626 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100627 return;
Niels Möller530ead42018-10-04 14:28:39 +0200628 }
629
630 {
631 rtc::CritScope lock(&ts_stats_lock_);
632 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
633 }
Niels Möller530ead42018-10-04 14:28:39 +0200634}
635
636int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200637 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200638 return _outputAudioLevel.LevelFullRange();
639}
640
641double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200642 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200643 return _outputAudioLevel.TotalEnergy();
644}
645
646double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200647 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200648 return _outputAudioLevel.TotalDuration();
649}
650
651void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200652 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200653 rtc::CritScope cs(&volume_settings_critsect_);
654 _outputGain = scaling;
655}
656
Niels Möller530ead42018-10-04 14:28:39 +0200657void ChannelReceive::RegisterReceiverCongestionControlObjects(
658 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200659 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200660 RTC_DCHECK(packet_router);
661 RTC_DCHECK(!packet_router_);
662 constexpr bool remb_candidate = false;
663 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
664 packet_router_ = packet_router;
665}
666
667void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200668 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200669 RTC_DCHECK(packet_router_);
670 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
671 packet_router_ = nullptr;
672}
673
Niels Möller349ade32018-11-16 09:50:42 +0100674CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200675 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200676 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100677 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200678
679 // The jitter statistics is updated for each received RTP packet and is
680 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200681 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200682 StreamStatistician* statistician =
683 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
684 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200685 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200686 }
687
Niels Möllerd77cc242019-08-22 09:40:25 +0200688 stats.cumulativeLost = rtp_stats.packets_lost;
689 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200690
691 // --- RTT
692 stats.rttMs = GetRTT();
693
694 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200695 if (statistician) {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200696 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
697
698 stats.header_and_padding_bytes_rcvd =
699 rtp_stats.packet_counter.header_bytes +
700 rtp_stats.packet_counter.padding_bytes;
Niels Möllerd77cc242019-08-22 09:40:25 +0200701 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200702 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200703 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200704 } else {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200705 stats.payload_bytes_rcvd = 0;
706 stats.header_and_padding_bytes_rcvd = 0;
Henrik Boström01738c62019-04-15 17:32:00 +0200707 stats.packetsReceived = 0;
708 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200709 }
710
Niels Möller530ead42018-10-04 14:28:39 +0200711 // --- Timestamps
712 {
713 rtc::CritScope lock(&ts_stats_lock_);
714 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
715 }
Niels Möller80c67622018-11-12 13:22:47 +0100716 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200717}
718
Niels Möller349ade32018-11-16 09:50:42 +0100719void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200720 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200721 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100722 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200723 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
724 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100725 } else {
726 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200727 kDefaultMaxReorderingThreshold);
728 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100729 }
Niels Möller530ead42018-10-04 14:28:39 +0200730}
731
732// Called when we are missing one or more packets.
733int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
734 int length) {
735 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
736}
737
Niels Möllerdced9f62018-11-19 10:27:07 +0100738void ChannelReceive::SetAssociatedSendChannel(
739 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200740 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200741 rtc::CritScope lock(&assoc_send_channel_lock_);
742 associated_send_channel_ = channel;
743}
744
Niels Möller80c67622018-11-12 13:22:47 +0100745NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200746 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100747 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200748 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100749 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200750}
751
Niels Möller80c67622018-11-12 13:22:47 +0100752AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200753 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100754 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200755 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100756 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200757}
758
759uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200760 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
761 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200762 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200763 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200764}
765
Niels Möller349ade32018-11-16 09:50:42 +0100766void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200767 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100768 // Limit to range accepted by both VoE and ACM, so we're at least getting as
769 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100770 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
771 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200772 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200773 RTC_DLOG(LS_ERROR)
774 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200775 }
Niels Möller530ead42018-10-04 14:28:39 +0200776}
777
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200778bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
779 int64_t* time_ms) const {
Niels Möller349ade32018-11-16 09:50:42 +0100780 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200781 {
782 rtc::CritScope lock(&video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200783 if (!playout_timestamp_rtp_time_ms_)
784 return false;
785 *rtp_timestamp = playout_timestamp_rtp_;
786 *time_ms = playout_timestamp_rtp_time_ms_.value();
787 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200788 }
Niels Möller530ead42018-10-04 14:28:39 +0200789}
790
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200791void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
792 int64_t time_ms) {
793 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
794 rtc::CritScope lock(&video_sync_lock_);
795 playout_timestamp_ntp_ = ntp_timestamp_ms;
796 playout_timestamp_ntp_time_ms_ = time_ms;
797}
798
799absl::optional<int64_t>
800ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const {
801 RTC_DCHECK(worker_thread_checker_.IsCurrent());
802 rtc::CritScope lock(&video_sync_lock_);
803 if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_)
804 return absl::nullopt;
805
806 int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_;
807 return *playout_timestamp_ntp_ + elapsed_ms;
808}
809
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100810bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200811 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100812}
813
814int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200815 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100816}
817
Niels Möller530ead42018-10-04 14:28:39 +0200818absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200819 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200820 Syncable::Info info;
821 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
822 &info.capture_time_ntp_frac, nullptr, nullptr,
823 &info.capture_time_source_clock) != 0) {
824 return absl::nullopt;
825 }
826 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000827 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200828 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
829 return absl::nullopt;
830 }
831 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
832 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
833 }
834 return info;
835}
836
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200837void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200838 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200839
840 if (!jitter_buffer_playout_timestamp_) {
841 // This can happen if this channel has not received any RTP packets. In
842 // this case, NetEq is not capable of computing a playout timestamp.
843 return;
844 }
845
846 uint16_t delay_ms = 0;
847 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
848 RTC_DLOG(LS_WARNING)
849 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100850 " playout delay from the ADM";
Niels Möller530ead42018-10-04 14:28:39 +0200851 return;
852 }
853
854 RTC_DCHECK(jitter_buffer_playout_timestamp_);
855 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
856
857 // Remove the playout delay.
858 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
859
860 {
861 rtc::CritScope lock(&video_sync_lock_);
Åsa Persson8a5776a2020-02-18 16:33:21 +0100862 if (!rtcp && playout_timestamp != playout_timestamp_rtp_) {
Niels Möller530ead42018-10-04 14:28:39 +0200863 playout_timestamp_rtp_ = playout_timestamp;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200864 playout_timestamp_rtp_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200865 }
866 playout_delay_ms_ = delay_ms;
867 }
868}
869
870int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200871 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200872 // Default to the playout frequency if we've not gotten any packets yet.
873 // TODO(ossu): Zero clockrate can only happen if we've added an external
874 // decoder for a format we don't support internally. Remove once that way of
875 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +0200876 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
877 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
878 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100879 return (decoder && decoder->second.clockrate_hz != 0)
880 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200881 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200882}
883
884int64_t ChannelReceive::GetRTT() const {
Niels Möller530ead42018-10-04 14:28:39 +0200885 std::vector<RTCPReportBlock> report_blocks;
886 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
887
888 // TODO(nisse): Could we check the return value from the ->RTT() call below,
889 // instead of checking if we have any report blocks?
890 if (report_blocks.empty()) {
891 rtc::CritScope lock(&assoc_send_channel_lock_);
892 // Tries to get RTT from an associated channel.
893 if (!associated_send_channel_) {
894 return 0;
895 }
896 return associated_send_channel_->GetRTT();
897 }
898
899 int64_t rtt = 0;
900 int64_t avg_rtt = 0;
901 int64_t max_rtt = 0;
902 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100903 // TODO(nisse): This method computes RTT based on sender reports, even though
904 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200905 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
906 0) {
907 return 0;
908 }
909 return rtt;
910}
911
Niels Möller349ade32018-11-16 09:50:42 +0100912} // namespace
913
914std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100915 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100916 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100917 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +0100918 AudioDeviceModule* audio_device_module,
Niels Möller349ade32018-11-16 09:50:42 +0100919 Transport* rtcp_send_transport,
920 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200921 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100922 uint32_t remote_ssrc,
923 size_t jitter_buffer_max_packets,
924 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100925 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100926 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100927 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
928 absl::optional<AudioCodecPairId> codec_pair_id,
929 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
930 const webrtc::CryptoOptions& crypto_options) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200931 return std::make_unique<ChannelReceive>(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100932 clock, module_process_thread, neteq_factory, audio_device_module,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800933 rtcp_send_transport, rtc_event_log, local_ssrc, remote_ssrc,
934 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100935 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
936 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100937}
938
Niels Möller530ead42018-10-04 14:28:39 +0200939} // namespace voe
940} // namespace webrtc