blob: e19a49dfd58d052281c240f178ef67e085b22d70 [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"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020021#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller349ade32018-11-16 09:50:42 +010022#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020023#include "audio/channel_send.h"
24#include "audio/utility/audio_frame_operations.h"
25#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möllered44f542019-07-30 15:15:59 +020026#include "modules/audio_coding/acm2/acm_receiver.h"
Niels Möller530ead42018-10-04 14:28:39 +020027#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
28#include "modules/audio_device/include/audio_device.h"
29#include "modules/pacing/packet_router.h"
30#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010031#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
32#include "modules/rtp_rtcp/include/rtp_rtcp.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020034#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010035#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020036#include "modules/utility/include/process_thread.h"
37#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#include "rtc_base/format_macros.h"
40#include "rtc_base/location.h"
41#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010042#include "rtc_base/numerics/safe_minmax.h"
43#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020044#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020046#include "system_wrappers/include/metrics.h"
47
48namespace webrtc {
49namespace voe {
50
51namespace {
52
53constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020054
55// Video Sync.
56constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
57constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
58
Niels Möllerafb5dbb2019-02-15 15:21:47 +010059RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000060 const MediaTransportEncodedAudioFrame& frame,
61 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010062 webrtc::RTPHeader rtp_header;
63 rtp_header.payloadType = frame.payload_type();
64 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
65 rtp_header.timestamp = frame.starting_sample_index();
66 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020067
Sergey Silkine049eba2019-02-18 09:52:26 +000068 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020069
70 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010071 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020072}
73
Niels Möllered44f542019-07-30 15:15:59 +020074AudioCodingModule::Config AcmConfig(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010075 NetEqFactory* neteq_factory,
Niels Möllered44f542019-07-30 15:15:59 +020076 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
77 absl::optional<AudioCodecPairId> codec_pair_id,
78 size_t jitter_buffer_max_packets,
79 bool jitter_buffer_fast_playout) {
80 AudioCodingModule::Config acm_config;
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010081 acm_config.neteq_factory = neteq_factory;
Niels Möllered44f542019-07-30 15:15:59 +020082 acm_config.decoder_factory = decoder_factory;
83 acm_config.neteq_config.codec_pair_id = codec_pair_id;
84 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
85 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
86 acm_config.neteq_config.enable_muted_state = true;
87
88 return acm_config;
89}
90
Niels Möller349ade32018-11-16 09:50:42 +010091class ChannelReceive : public ChannelReceiveInterface,
92 public MediaTransportAudioSinkInterface {
93 public:
94 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010095 ChannelReceive(Clock* clock,
96 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010097 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +010098 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -070099 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100100 Transport* rtcp_send_transport,
101 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200102 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100103 uint32_t remote_ssrc,
104 size_t jitter_buffer_max_packets,
105 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100106 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100107 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100108 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
109 absl::optional<AudioCodecPairId> codec_pair_id,
110 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
111 const webrtc::CryptoOptions& crypto_options);
112 ~ChannelReceive() override;
113
114 void SetSink(AudioSinkInterface* sink) override;
115
116 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
117
118 // API methods
119
120 void StartPlayout() override;
121 void StopPlayout() override;
122
123 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000124 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
125 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100126
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100127 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100128
129 // RtpPacketSinkInterface.
130 void OnRtpPacket(const RtpPacketReceived& packet) override;
131
132 // Muting, Volume and Level.
133 void SetChannelOutputVolumeScaling(float scaling) override;
134 int GetSpeechOutputLevelFullRange() const override;
135 // See description of "totalAudioEnergy" in the WebRTC stats spec:
136 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
137 double GetTotalOutputEnergy() const override;
138 double GetTotalOutputDuration() const override;
139
140 // Stats.
141 NetworkStatistics GetNetworkStatistics() const override;
142 AudioDecodingCallStats GetDecodingCallStatistics() const override;
143
144 // Audio+Video Sync.
145 uint32_t GetDelayEstimate() const override;
146 void SetMinimumPlayoutDelay(int delayMs) override;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200147 bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
148 int64_t* time_ms) const override;
149 void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
150 int64_t time_ms) override;
151 absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs(
152 int64_t now_ms) const override;
Niels Möller349ade32018-11-16 09:50:42 +0100153
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100154 // Audio quality.
155 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
156 int GetBaseMinimumPlayoutDelayMs() const override;
157
Niels Möller349ade32018-11-16 09:50:42 +0100158 // Produces the transport-related timestamps; current_delay_ms is left unset.
159 absl::optional<Syncable::Info> GetSyncInfo() const override;
160
Niels Möller349ade32018-11-16 09:50:42 +0100161 void RegisterReceiverCongestionControlObjects(
162 PacketRouter* packet_router) override;
163 void ResetReceiverCongestionControlObjects() override;
164
165 CallReceiveStatistics GetRTCPStatistics() const override;
166 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
167
168 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
169 int sample_rate_hz,
170 AudioFrame* audio_frame) override;
171
172 int PreferredSampleRate() const override;
173
174 // Associate to a send channel.
175 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100176 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100177
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700178 // TODO(sukhanov): Return const pointer. It requires making media transport
179 // getters like GetLatestTargetTransferRate to be also const.
180 MediaTransportInterface* media_transport() const {
181 return media_transport_config_.media_transport;
182 }
183
Niels Möller349ade32018-11-16 09:50:42 +0100184 private:
Niels Möllered44f542019-07-30 15:15:59 +0200185 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100186 size_t packet_length,
187 const RTPHeader& header);
188 int ResendPackets(const uint16_t* sequence_numbers, int length);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200189 void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms);
Niels Möller349ade32018-11-16 09:50:42 +0100190
191 int GetRtpTimestampRateHz() const;
192 int64_t GetRTT() const;
193
194 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000195 void OnData(uint64_t channel_id,
196 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100197
Niels Möllered44f542019-07-30 15:15:59 +0200198 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
199 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100200
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100201 bool Playing() const {
202 rtc::CritScope lock(&playing_lock_);
203 return playing_;
204 }
205
Niels Möller349ade32018-11-16 09:50:42 +0100206 // Thread checkers document and lock usage of some methods to specific threads
207 // we know about. The goal is to eventually split up voe::ChannelReceive into
208 // parts with single-threaded semantics, and thereby reduce the need for
209 // locks.
210 rtc::ThreadChecker worker_thread_checker_;
211 rtc::ThreadChecker module_process_thread_checker_;
212 // Methods accessed from audio and video threads are checked for sequential-
213 // only access. We don't necessarily own and control these threads, so thread
214 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
215 // audio thread to another, but access is still sequential.
216 rtc::RaceChecker audio_thread_race_checker_;
217 rtc::RaceChecker video_capture_thread_race_checker_;
218 rtc::CriticalSection _callbackCritSect;
219 rtc::CriticalSection volume_settings_critsect_;
220
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100221 rtc::CriticalSection playing_lock_;
222 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100223
224 RtcEventLog* const event_log_;
225
226 // Indexed by payload type.
227 std::map<uint8_t, int> payload_type_frequencies_;
228
229 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
230 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
231 const uint32_t remote_ssrc_;
232
Chen Xing054e3bb2019-08-02 10:29:26 +0000233 // Info for GetSyncInfo is updated on network or worker thread, and queried on
234 // the worker thread.
235 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100236 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000237 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100238 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000239 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100240
Niels Möllered44f542019-07-30 15:15:59 +0200241 // The AcmReceiver is thread safe, using its own lock.
242 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100243 AudioSinkInterface* audio_sink_ = nullptr;
244 AudioLevel _outputAudioLevel;
245
246 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
247
248 // Timestamp of the audio pulled from NetEq.
249 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
250
251 rtc::CriticalSection video_sync_lock_;
252 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200253 absl::optional<int64_t> playout_timestamp_rtp_time_ms_
254 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100255 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200256 absl::optional<int64_t> playout_timestamp_ntp_
257 RTC_GUARDED_BY(video_sync_lock_);
258 absl::optional<int64_t> playout_timestamp_ntp_time_ms_
259 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100260
261 rtc::CriticalSection ts_stats_lock_;
262
263 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
264 // The rtp timestamp of the first played out audio frame.
265 int64_t capture_start_rtp_time_stamp_;
266 // The capture ntp time (in local timebase) of the first played out audio
267 // frame.
268 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
269
270 // uses
271 ProcessThread* _moduleProcessThreadPtr;
272 AudioDeviceModule* _audioDeviceModulePtr;
273 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
274
275 // An associated send channel.
276 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100277 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100278 RTC_GUARDED_BY(assoc_send_channel_lock_);
279
280 PacketRouter* packet_router_ = nullptr;
281
282 rtc::ThreadChecker construction_thread_;
283
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700284 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100285
286 // E2EE Audio Frame Decryption
287 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
288 webrtc::CryptoOptions crypto_options_;
289};
Niels Möller530ead42018-10-04 14:28:39 +0200290
Niels Möllered44f542019-07-30 15:15:59 +0200291void ChannelReceive::OnReceivedPayloadData(
292 rtc::ArrayView<const uint8_t> payload,
293 const RTPHeader& rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200294 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700295 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200296
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100297 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200298 // Avoid inserting into NetEQ when we are not playing. Count the
299 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200300 return;
Niels Möller530ead42018-10-04 14:28:39 +0200301 }
302
303 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200304 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200305 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
306 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200307 return;
Niels Möller530ead42018-10-04 14:28:39 +0200308 }
309
310 int64_t round_trip_time = 0;
311 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
312
Niels Möllered44f542019-07-30 15:15:59 +0200313 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200314 if (!nack_list.empty()) {
315 // Can't use nack_list.data() since it's not supported by all
316 // compilers.
317 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
318 }
Niels Möller530ead42018-10-04 14:28:39 +0200319}
320
Niels Möller7d76a312018-10-26 12:57:07 +0200321// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000322void ChannelReceive::OnData(uint64_t channel_id,
323 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700324 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200325
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100326 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200327 // Avoid inserting into NetEQ when we are not playing. Count the
328 // packet as discarded.
329 return;
330 }
331
332 // Send encoded audio frame to Decoder / NetEq.
Niels Möllered44f542019-07-30 15:15:59 +0200333 if (acm_receiver_.InsertPacket(
334 CreateRTPHeaderForMediaTransportFrame(frame, channel_id),
335 frame.encoded_data()) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200336 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
337 "push data to the ACM";
338 }
339}
340
Niels Möller530ead42018-10-04 14:28:39 +0200341AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
342 int sample_rate_hz,
343 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100344 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200345 audio_frame->sample_rate_hz_ = sample_rate_hz;
346
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200347 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100348
Niels Möller530ead42018-10-04 14:28:39 +0200349 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
350 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200351 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
352 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200353 RTC_DLOG(LS_ERROR)
354 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
355 // In all likelihood, the audio in this frame is garbage. We return an
356 // error so that the audio mixer module doesn't add it to the mix. As
357 // a result, it won't be played out and the actions skipped here are
358 // irrelevant.
359 return AudioMixer::Source::AudioFrameInfo::kError;
360 }
361
362 if (muted) {
363 // TODO(henrik.lundin): We should be able to do better than this. But we
364 // will have to go through all the cases below where the audio samples may
365 // be used, and handle the muted case in some way.
366 AudioFrameOperations::Mute(audio_frame);
367 }
368
369 {
370 // Pass the audio buffers to an optional sink callback, before applying
371 // scaling/panning, as that applies to the mix operation.
372 // External recipients of the audio (e.g. via AudioTrack), will do their
373 // own mixing/dynamic processing.
374 rtc::CritScope cs(&_callbackCritSect);
375 if (audio_sink_) {
376 AudioSinkInterface::Data data(
377 audio_frame->data(), audio_frame->samples_per_channel_,
378 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
379 audio_frame->timestamp_);
380 audio_sink_->OnData(data);
381 }
382 }
383
384 float output_gain = 1.0f;
385 {
386 rtc::CritScope cs(&volume_settings_critsect_);
387 output_gain = _outputGain;
388 }
389
390 // Output volume scaling
391 if (output_gain < 0.99f || output_gain > 1.01f) {
392 // TODO(solenberg): Combine with mute state - this can cause clicks!
393 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
394 }
395
396 // Measure audio level (0-9)
397 // TODO(henrik.lundin) Use the |muted| information here too.
398 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
399 // https://crbug.com/webrtc/7517).
400 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
401
402 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
403 // The first frame with a valid rtp timestamp.
404 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
405 }
406
407 if (capture_start_rtp_time_stamp_ >= 0) {
408 // audio_frame.timestamp_ should be valid from now on.
409
410 // Compute elapsed time.
411 int64_t unwrap_timestamp =
412 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
413 audio_frame->elapsed_time_ms_ =
414 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
415 (GetRtpTimestampRateHz() / 1000);
416
417 {
418 rtc::CritScope lock(&ts_stats_lock_);
419 // Compute ntp time.
420 audio_frame->ntp_time_ms_ =
421 ntp_estimator_.Estimate(audio_frame->timestamp_);
422 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
423 if (audio_frame->ntp_time_ms_ > 0) {
424 // Compute |capture_start_ntp_time_ms_| so that
425 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
426 capture_start_ntp_time_ms_ =
427 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
428 }
429 }
430 }
431
432 {
433 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200434 acm_receiver_.TargetDelayMs());
435 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200436 rtc::CritScope lock(&video_sync_lock_);
437 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
438 jitter_buffer_delay + playout_delay_ms_);
439 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
440 jitter_buffer_delay);
441 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
442 playout_delay_ms_);
443 }
444
445 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
446 : AudioMixer::Source::AudioFrameInfo::kNormal;
447}
448
449int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100450 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200451 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200452 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
453 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200454}
455
456ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100457 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200458 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100459 NetEqFactory* neteq_factory,
Niels Möller530ead42018-10-04 14:28:39 +0200460 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700461 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200462 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200463 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200464 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200465 uint32_t remote_ssrc,
466 size_t jitter_buffer_max_packets,
467 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100468 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100469 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200470 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700471 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700472 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700473 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200474 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100475 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200476 remote_ssrc_(remote_ssrc),
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100477 acm_receiver_(AcmConfig(neteq_factory,
478 decoder_factory,
Niels Möllered44f542019-07-30 15:15:59 +0200479 codec_pair_id,
480 jitter_buffer_max_packets,
481 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200482 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100483 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200484 playout_timestamp_rtp_(0),
485 playout_delay_ms_(0),
486 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
487 capture_start_rtp_time_stamp_(-1),
488 capture_start_ntp_time_ms_(-1),
489 _moduleProcessThreadPtr(module_process_thread),
490 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200491 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700492 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700493 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700494 frame_decryptor_(frame_decryptor),
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200495 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100496 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200497 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100498
Niels Möller530ead42018-10-04 14:28:39 +0200499 RTC_DCHECK(module_process_thread);
500 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200501
502 acm_receiver_.ResetInitialDelay();
503 acm_receiver_.SetMinimumDelay(0);
504 acm_receiver_.SetMaximumDelay(0);
505 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200506
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200507 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200508
509 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
510 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100511 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200512 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100513 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200514 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200515 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200516 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200517 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200518
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100519 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200520 _rtpRtcpModule->SetSendingMediaStatus(false);
521 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200522
Niels Möller530ead42018-10-04 14:28:39 +0200523 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
524
Niels Möllerb6220d92019-08-29 13:47:09 +0200525 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200526 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200527
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700528 if (media_transport()) {
529 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200530 }
Niels Möller530ead42018-10-04 14:28:39 +0200531}
532
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100533ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200534 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200535
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700536 if (media_transport()) {
537 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200538 }
539
Niels Möller530ead42018-10-04 14:28:39 +0200540 StopPlayout();
541
Niels Möller530ead42018-10-04 14:28:39 +0200542 if (_moduleProcessThreadPtr)
543 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200544}
545
546void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200547 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200548 rtc::CritScope cs(&_callbackCritSect);
549 audio_sink_ = sink;
550}
551
Niels Möller80c67622018-11-12 13:22:47 +0100552void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200553 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100554 rtc::CritScope lock(&playing_lock_);
555 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200556}
557
Niels Möller80c67622018-11-12 13:22:47 +0100558void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200559 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100560 rtc::CritScope lock(&playing_lock_);
561 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200562 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200563}
564
Jonas Olssona4d87372019-07-05 19:08:33 +0200565absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
566 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200567 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200568 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200569}
570
Niels Möller530ead42018-10-04 14:28:39 +0200571void ChannelReceive::SetReceiveCodecs(
572 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200573 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200574 for (const auto& kv : codecs) {
575 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
576 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
577 }
Niels Möllered44f542019-07-30 15:15:59 +0200578 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200579}
580
Niels Möller349ade32018-11-16 09:50:42 +0100581// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200582void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
583 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200584
585 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000586 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200587 last_received_rtp_timestamp_ = packet.Timestamp();
588 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200589 }
590
591 // Store playout timestamp for the received RTP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200592 UpdatePlayoutTimestamp(false, now_ms);
Niels Möller530ead42018-10-04 14:28:39 +0200593
594 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
595 if (it == payload_type_frequencies_.end())
596 return;
597 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
598 RtpPacketReceived packet_copy(packet);
599 packet_copy.set_payload_type_frequency(it->second);
600
601 rtp_receive_statistics_->OnRtpPacket(packet_copy);
602
603 RTPHeader header;
604 packet_copy.GetHeader(&header);
605
606 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
607}
608
Niels Möllered44f542019-07-30 15:15:59 +0200609void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200610 size_t packet_length,
611 const RTPHeader& header) {
612 const uint8_t* payload = packet + header.headerLength;
613 assert(packet_length >= header.headerLength);
614 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200615
Benjamin Wright84583f62018-10-04 14:22:34 -0700616 size_t payload_data_length = payload_length - header.paddingLength;
617
618 // E2EE Custom Audio Frame Decryption (This is optional).
619 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
620 rtc::Buffer decrypted_audio_payload;
621 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000622 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700623 cricket::MEDIA_TYPE_AUDIO, payload_length);
624 decrypted_audio_payload.SetSize(max_plaintext_size);
625
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000626 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
627 header.arrOfCSRCs + header.numCSRCs);
628 const FrameDecryptorInterface::Result decrypt_result =
629 frame_decryptor_->Decrypt(
630 cricket::MEDIA_TYPE_AUDIO, csrcs,
631 /*additional_data=*/nullptr,
632 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
633 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700634
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000635 if (decrypt_result.IsOk()) {
636 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
637 } else {
638 // Interpret failures as a silent frame.
639 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700640 }
641
Benjamin Wright84583f62018-10-04 14:22:34 -0700642 payload = decrypted_audio_payload.data();
643 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700644 } else if (crypto_options_.sframe.require_frame_encryption) {
645 RTC_DLOG(LS_ERROR)
646 << "FrameDecryptor required but not set, dropping packet";
647 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700648 }
649
Niels Möllered44f542019-07-30 15:15:59 +0200650 OnReceivedPayloadData(
651 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200652}
653
Niels Möller349ade32018-11-16 09:50:42 +0100654// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100655void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200656 // Store playout timestamp for the received RTCP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200657 UpdatePlayoutTimestamp(true, rtc::TimeMillis());
Niels Möller530ead42018-10-04 14:28:39 +0200658
659 // Deliver RTCP packet to RTP/RTCP module for parsing
660 _rtpRtcpModule->IncomingRtcpPacket(data, length);
661
662 int64_t rtt = GetRTT();
663 if (rtt == 0) {
664 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100665 return;
Niels Möller530ead42018-10-04 14:28:39 +0200666 }
667
Niels Möller530ead42018-10-04 14:28:39 +0200668 uint32_t ntp_secs = 0;
669 uint32_t ntp_frac = 0;
670 uint32_t rtp_timestamp = 0;
671 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
672 &rtp_timestamp)) {
673 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100674 return;
Niels Möller530ead42018-10-04 14:28:39 +0200675 }
676
677 {
678 rtc::CritScope lock(&ts_stats_lock_);
679 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
680 }
Niels Möller530ead42018-10-04 14:28:39 +0200681}
682
683int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200684 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200685 return _outputAudioLevel.LevelFullRange();
686}
687
688double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200689 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200690 return _outputAudioLevel.TotalEnergy();
691}
692
693double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200694 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200695 return _outputAudioLevel.TotalDuration();
696}
697
698void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200699 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200700 rtc::CritScope cs(&volume_settings_critsect_);
701 _outputGain = scaling;
702}
703
Niels Möller530ead42018-10-04 14:28:39 +0200704void ChannelReceive::RegisterReceiverCongestionControlObjects(
705 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200706 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200707 RTC_DCHECK(packet_router);
708 RTC_DCHECK(!packet_router_);
709 constexpr bool remb_candidate = false;
710 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
711 packet_router_ = packet_router;
712}
713
714void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200715 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200716 RTC_DCHECK(packet_router_);
717 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
718 packet_router_ = nullptr;
719}
720
Niels Möller349ade32018-11-16 09:50:42 +0100721CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200722 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200723 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100724 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200725
726 // The jitter statistics is updated for each received RTP packet and is
727 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200728 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200729 StreamStatistician* statistician =
730 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
731 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200732 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200733 }
734
Niels Möllerd77cc242019-08-22 09:40:25 +0200735 stats.cumulativeLost = rtp_stats.packets_lost;
736 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200737
738 // --- RTT
739 stats.rttMs = GetRTT();
740
741 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200742 if (statistician) {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200743 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
744
745 stats.header_and_padding_bytes_rcvd =
746 rtp_stats.packet_counter.header_bytes +
747 rtp_stats.packet_counter.padding_bytes;
Niels Möllerd77cc242019-08-22 09:40:25 +0200748 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200749 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200750 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200751 } else {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200752 stats.payload_bytes_rcvd = 0;
753 stats.header_and_padding_bytes_rcvd = 0;
Henrik Boström01738c62019-04-15 17:32:00 +0200754 stats.packetsReceived = 0;
755 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200756 }
757
Niels Möller530ead42018-10-04 14:28:39 +0200758 // --- Timestamps
759 {
760 rtc::CritScope lock(&ts_stats_lock_);
761 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
762 }
Niels Möller80c67622018-11-12 13:22:47 +0100763 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200764}
765
Niels Möller349ade32018-11-16 09:50:42 +0100766void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200767 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200768 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100769 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200770 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
771 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100772 } else {
773 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200774 kDefaultMaxReorderingThreshold);
775 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100776 }
Niels Möller530ead42018-10-04 14:28:39 +0200777}
778
779// Called when we are missing one or more packets.
780int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
781 int length) {
782 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
783}
784
Niels Möllerdced9f62018-11-19 10:27:07 +0100785void ChannelReceive::SetAssociatedSendChannel(
786 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200787 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200788 rtc::CritScope lock(&assoc_send_channel_lock_);
789 associated_send_channel_ = channel;
790}
791
Niels Möller80c67622018-11-12 13:22:47 +0100792NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200793 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100794 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200795 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100796 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200797}
798
Niels Möller80c67622018-11-12 13:22:47 +0100799AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200800 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100801 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200802 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100803 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200804}
805
806uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200807 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
808 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200809 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200810 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200811}
812
Niels Möller349ade32018-11-16 09:50:42 +0100813void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200814 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100815 // Limit to range accepted by both VoE and ACM, so we're at least getting as
816 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100817 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
818 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200819 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200820 RTC_DLOG(LS_ERROR)
821 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200822 }
Niels Möller530ead42018-10-04 14:28:39 +0200823}
824
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200825bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
826 int64_t* time_ms) const {
Niels Möller349ade32018-11-16 09:50:42 +0100827 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200828 {
829 rtc::CritScope lock(&video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200830 if (!playout_timestamp_rtp_time_ms_)
831 return false;
832 *rtp_timestamp = playout_timestamp_rtp_;
833 *time_ms = playout_timestamp_rtp_time_ms_.value();
834 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200835 }
Niels Möller530ead42018-10-04 14:28:39 +0200836}
837
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200838void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
839 int64_t time_ms) {
840 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
841 rtc::CritScope lock(&video_sync_lock_);
842 playout_timestamp_ntp_ = ntp_timestamp_ms;
843 playout_timestamp_ntp_time_ms_ = time_ms;
844}
845
846absl::optional<int64_t>
847ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const {
848 RTC_DCHECK(worker_thread_checker_.IsCurrent());
849 rtc::CritScope lock(&video_sync_lock_);
850 if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_)
851 return absl::nullopt;
852
853 int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_;
854 return *playout_timestamp_ntp_ + elapsed_ms;
855}
856
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100857bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200858 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100859}
860
861int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200862 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100863}
864
Niels Möller530ead42018-10-04 14:28:39 +0200865absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200866 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200867 Syncable::Info info;
868 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
869 &info.capture_time_ntp_frac, nullptr, nullptr,
870 &info.capture_time_source_clock) != 0) {
871 return absl::nullopt;
872 }
873 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000874 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200875 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
876 return absl::nullopt;
877 }
878 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
879 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
880 }
881 return info;
882}
883
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200884void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200885 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200886
887 if (!jitter_buffer_playout_timestamp_) {
888 // This can happen if this channel has not received any RTP packets. In
889 // this case, NetEq is not capable of computing a playout timestamp.
890 return;
891 }
892
893 uint16_t delay_ms = 0;
894 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
895 RTC_DLOG(LS_WARNING)
896 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
897 << " playout delay from the ADM";
898 return;
899 }
900
901 RTC_DCHECK(jitter_buffer_playout_timestamp_);
902 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
903
904 // Remove the playout delay.
905 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
906
907 {
908 rtc::CritScope lock(&video_sync_lock_);
909 if (!rtcp) {
910 playout_timestamp_rtp_ = playout_timestamp;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200911 playout_timestamp_rtp_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200912 }
913 playout_delay_ms_ = delay_ms;
914 }
915}
916
917int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200918 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200919 // Default to the playout frequency if we've not gotten any packets yet.
920 // TODO(ossu): Zero clockrate can only happen if we've added an external
921 // decoder for a format we don't support internally. Remove once that way of
922 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +0200923 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
924 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
925 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100926 return (decoder && decoder->second.clockrate_hz != 0)
927 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200928 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200929}
930
931int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700932 if (media_transport()) {
933 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800934 if (target_rate.has_value()) {
935 return target_rate->network_estimate.round_trip_time.ms();
936 }
937
938 return 0;
939 }
Niels Möller530ead42018-10-04 14:28:39 +0200940 std::vector<RTCPReportBlock> report_blocks;
941 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
942
943 // TODO(nisse): Could we check the return value from the ->RTT() call below,
944 // instead of checking if we have any report blocks?
945 if (report_blocks.empty()) {
946 rtc::CritScope lock(&assoc_send_channel_lock_);
947 // Tries to get RTT from an associated channel.
948 if (!associated_send_channel_) {
949 return 0;
950 }
951 return associated_send_channel_->GetRTT();
952 }
953
954 int64_t rtt = 0;
955 int64_t avg_rtt = 0;
956 int64_t max_rtt = 0;
957 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100958 // TODO(nisse): This method computes RTT based on sender reports, even though
959 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200960 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
961 0) {
962 return 0;
963 }
964 return rtt;
965}
966
Niels Möller349ade32018-11-16 09:50:42 +0100967} // namespace
968
969std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100970 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100971 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100972 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +0100973 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700974 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100975 Transport* rtcp_send_transport,
976 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200977 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100978 uint32_t remote_ssrc,
979 size_t jitter_buffer_max_packets,
980 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100981 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100982 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100983 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
984 absl::optional<AudioCodecPairId> codec_pair_id,
985 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
986 const webrtc::CryptoOptions& crypto_options) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200987 return std::make_unique<ChannelReceive>(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100988 clock, module_process_thread, neteq_factory, audio_device_module,
989 media_transport_config, rtcp_send_transport, rtc_event_log, local_ssrc,
990 remote_ssrc, jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100991 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
992 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100993}
994
Niels Möller530ead42018-10-04 14:28:39 +0200995} // namespace voe
996} // namespace webrtc