blob: 502818f1c9b1ab2ff2122b4a09f4d30f878ef014 [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"
Yves Gerey988cc082018-10-23 12:03:01 +020035#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020036#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010037#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020038#include "modules/utility/include/process_thread.h"
39#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020041#include "rtc_base/format_macros.h"
42#include "rtc_base/location.h"
43#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010044#include "rtc_base/numerics/safe_minmax.h"
45#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020046#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080047#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020048#include "system_wrappers/include/metrics.h"
49
50namespace webrtc {
51namespace voe {
52
53namespace {
54
55constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020056
57// Video Sync.
58constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
59constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
60
Niels Möllerafb5dbb2019-02-15 15:21:47 +010061RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000062 const MediaTransportEncodedAudioFrame& frame,
63 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010064 webrtc::RTPHeader rtp_header;
65 rtp_header.payloadType = frame.payload_type();
66 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
67 rtp_header.timestamp = frame.starting_sample_index();
68 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020069
Sergey Silkine049eba2019-02-18 09:52:26 +000070 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020071
72 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010073 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020074}
75
Niels Möllered44f542019-07-30 15:15:59 +020076AudioCodingModule::Config AcmConfig(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010077 NetEqFactory* neteq_factory,
Niels Möllered44f542019-07-30 15:15:59 +020078 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
79 absl::optional<AudioCodecPairId> codec_pair_id,
80 size_t jitter_buffer_max_packets,
81 bool jitter_buffer_fast_playout) {
82 AudioCodingModule::Config acm_config;
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010083 acm_config.neteq_factory = neteq_factory;
Niels Möllered44f542019-07-30 15:15:59 +020084 acm_config.decoder_factory = decoder_factory;
85 acm_config.neteq_config.codec_pair_id = codec_pair_id;
86 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
87 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
88 acm_config.neteq_config.enable_muted_state = true;
89
90 return acm_config;
91}
92
Niels Möller349ade32018-11-16 09:50:42 +010093class ChannelReceive : public ChannelReceiveInterface,
94 public MediaTransportAudioSinkInterface {
95 public:
96 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010097 ChannelReceive(Clock* clock,
98 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +010099 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +0100100 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700101 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100102 Transport* rtcp_send_transport,
103 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200104 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100105 uint32_t remote_ssrc,
106 size_t jitter_buffer_max_packets,
107 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100108 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100109 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100110 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
111 absl::optional<AudioCodecPairId> codec_pair_id,
112 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
113 const webrtc::CryptoOptions& crypto_options);
114 ~ChannelReceive() override;
115
116 void SetSink(AudioSinkInterface* sink) override;
117
118 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
119
120 // API methods
121
122 void StartPlayout() override;
123 void StopPlayout() override;
124
125 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000126 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
127 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100128
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100129 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100130
131 // RtpPacketSinkInterface.
132 void OnRtpPacket(const RtpPacketReceived& packet) override;
133
134 // Muting, Volume and Level.
135 void SetChannelOutputVolumeScaling(float scaling) override;
136 int GetSpeechOutputLevelFullRange() const override;
137 // See description of "totalAudioEnergy" in the WebRTC stats spec:
138 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
139 double GetTotalOutputEnergy() const override;
140 double GetTotalOutputDuration() const override;
141
142 // Stats.
143 NetworkStatistics GetNetworkStatistics() const override;
144 AudioDecodingCallStats GetDecodingCallStatistics() const override;
145
146 // Audio+Video Sync.
147 uint32_t GetDelayEstimate() const override;
148 void SetMinimumPlayoutDelay(int delayMs) override;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200149 bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
150 int64_t* time_ms) const override;
151 void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
152 int64_t time_ms) override;
153 absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs(
154 int64_t now_ms) const override;
Niels Möller349ade32018-11-16 09:50:42 +0100155
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100156 // Audio quality.
157 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
158 int GetBaseMinimumPlayoutDelayMs() const override;
159
Niels Möller349ade32018-11-16 09:50:42 +0100160 // Produces the transport-related timestamps; current_delay_ms is left unset.
161 absl::optional<Syncable::Info> GetSyncInfo() const override;
162
Niels Möller349ade32018-11-16 09:50:42 +0100163 void RegisterReceiverCongestionControlObjects(
164 PacketRouter* packet_router) override;
165 void ResetReceiverCongestionControlObjects() override;
166
167 CallReceiveStatistics GetRTCPStatistics() const override;
168 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
169
170 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
171 int sample_rate_hz,
172 AudioFrame* audio_frame) override;
173
174 int PreferredSampleRate() const override;
175
176 // Associate to a send channel.
177 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100178 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100179
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700180 // TODO(sukhanov): Return const pointer. It requires making media transport
181 // getters like GetLatestTargetTransferRate to be also const.
182 MediaTransportInterface* media_transport() const {
183 return media_transport_config_.media_transport;
184 }
185
Niels Möller349ade32018-11-16 09:50:42 +0100186 private:
Niels Möllered44f542019-07-30 15:15:59 +0200187 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100188 size_t packet_length,
189 const RTPHeader& header);
190 int ResendPackets(const uint16_t* sequence_numbers, int length);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200191 void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms);
Niels Möller349ade32018-11-16 09:50:42 +0100192
193 int GetRtpTimestampRateHz() const;
194 int64_t GetRTT() const;
195
196 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000197 void OnData(uint64_t channel_id,
198 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100199
Niels Möllered44f542019-07-30 15:15:59 +0200200 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
201 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100202
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100203 bool Playing() const {
204 rtc::CritScope lock(&playing_lock_);
205 return playing_;
206 }
207
Niels Möller349ade32018-11-16 09:50:42 +0100208 // Thread checkers document and lock usage of some methods to specific threads
209 // we know about. The goal is to eventually split up voe::ChannelReceive into
210 // parts with single-threaded semantics, and thereby reduce the need for
211 // locks.
212 rtc::ThreadChecker worker_thread_checker_;
213 rtc::ThreadChecker module_process_thread_checker_;
214 // Methods accessed from audio and video threads are checked for sequential-
215 // only access. We don't necessarily own and control these threads, so thread
216 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
217 // audio thread to another, but access is still sequential.
218 rtc::RaceChecker audio_thread_race_checker_;
219 rtc::RaceChecker video_capture_thread_race_checker_;
220 rtc::CriticalSection _callbackCritSect;
221 rtc::CriticalSection volume_settings_critsect_;
222
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100223 rtc::CriticalSection playing_lock_;
224 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100225
226 RtcEventLog* const event_log_;
227
228 // Indexed by payload type.
229 std::map<uint8_t, int> payload_type_frequencies_;
230
231 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
232 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
233 const uint32_t remote_ssrc_;
234
Chen Xing054e3bb2019-08-02 10:29:26 +0000235 // Info for GetSyncInfo is updated on network or worker thread, and queried on
236 // the worker thread.
237 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100238 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000239 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100240 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000241 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100242
Niels Möllered44f542019-07-30 15:15:59 +0200243 // The AcmReceiver is thread safe, using its own lock.
244 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100245 AudioSinkInterface* audio_sink_ = nullptr;
246 AudioLevel _outputAudioLevel;
247
248 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
249
250 // Timestamp of the audio pulled from NetEq.
251 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
252
253 rtc::CriticalSection video_sync_lock_;
254 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200255 absl::optional<int64_t> playout_timestamp_rtp_time_ms_
256 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100257 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200258 absl::optional<int64_t> playout_timestamp_ntp_
259 RTC_GUARDED_BY(video_sync_lock_);
260 absl::optional<int64_t> playout_timestamp_ntp_time_ms_
261 RTC_GUARDED_BY(video_sync_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100262
263 rtc::CriticalSection ts_stats_lock_;
264
265 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
266 // The rtp timestamp of the first played out audio frame.
267 int64_t capture_start_rtp_time_stamp_;
268 // The capture ntp time (in local timebase) of the first played out audio
269 // frame.
270 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
271
272 // uses
273 ProcessThread* _moduleProcessThreadPtr;
274 AudioDeviceModule* _audioDeviceModulePtr;
275 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
276
277 // An associated send channel.
278 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100279 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100280 RTC_GUARDED_BY(assoc_send_channel_lock_);
281
282 PacketRouter* packet_router_ = nullptr;
283
284 rtc::ThreadChecker construction_thread_;
285
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700286 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100287
288 // E2EE Audio Frame Decryption
289 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
290 webrtc::CryptoOptions crypto_options_;
291};
Niels Möller530ead42018-10-04 14:28:39 +0200292
Niels Möllered44f542019-07-30 15:15:59 +0200293void ChannelReceive::OnReceivedPayloadData(
294 rtc::ArrayView<const uint8_t> payload,
295 const RTPHeader& rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200296 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700297 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200298
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100299 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200300 // Avoid inserting into NetEQ when we are not playing. Count the
301 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200302 return;
Niels Möller530ead42018-10-04 14:28:39 +0200303 }
304
305 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200306 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200307 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
308 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200309 return;
Niels Möller530ead42018-10-04 14:28:39 +0200310 }
311
312 int64_t round_trip_time = 0;
313 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
314
Niels Möllered44f542019-07-30 15:15:59 +0200315 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200316 if (!nack_list.empty()) {
317 // Can't use nack_list.data() since it's not supported by all
318 // compilers.
319 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
320 }
Niels Möller530ead42018-10-04 14:28:39 +0200321}
322
Niels Möller7d76a312018-10-26 12:57:07 +0200323// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000324void ChannelReceive::OnData(uint64_t channel_id,
325 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700326 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200327
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100328 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200329 // Avoid inserting into NetEQ when we are not playing. Count the
330 // packet as discarded.
331 return;
332 }
333
334 // Send encoded audio frame to Decoder / NetEq.
Niels Möllered44f542019-07-30 15:15:59 +0200335 if (acm_receiver_.InsertPacket(
336 CreateRTPHeaderForMediaTransportFrame(frame, channel_id),
337 frame.encoded_data()) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200338 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
339 "push data to the ACM";
340 }
341}
342
Niels Möller530ead42018-10-04 14:28:39 +0200343AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
344 int sample_rate_hz,
345 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100346 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200347 audio_frame->sample_rate_hz_ = sample_rate_hz;
348
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200349 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100350
Niels Möller530ead42018-10-04 14:28:39 +0200351 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
352 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200353 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
354 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200355 RTC_DLOG(LS_ERROR)
356 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
357 // In all likelihood, the audio in this frame is garbage. We return an
358 // error so that the audio mixer module doesn't add it to the mix. As
359 // a result, it won't be played out and the actions skipped here are
360 // irrelevant.
361 return AudioMixer::Source::AudioFrameInfo::kError;
362 }
363
364 if (muted) {
365 // TODO(henrik.lundin): We should be able to do better than this. But we
366 // will have to go through all the cases below where the audio samples may
367 // be used, and handle the muted case in some way.
368 AudioFrameOperations::Mute(audio_frame);
369 }
370
371 {
372 // Pass the audio buffers to an optional sink callback, before applying
373 // scaling/panning, as that applies to the mix operation.
374 // External recipients of the audio (e.g. via AudioTrack), will do their
375 // own mixing/dynamic processing.
376 rtc::CritScope cs(&_callbackCritSect);
377 if (audio_sink_) {
378 AudioSinkInterface::Data data(
379 audio_frame->data(), audio_frame->samples_per_channel_,
380 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
381 audio_frame->timestamp_);
382 audio_sink_->OnData(data);
383 }
384 }
385
386 float output_gain = 1.0f;
387 {
388 rtc::CritScope cs(&volume_settings_critsect_);
389 output_gain = _outputGain;
390 }
391
392 // Output volume scaling
393 if (output_gain < 0.99f || output_gain > 1.01f) {
394 // TODO(solenberg): Combine with mute state - this can cause clicks!
395 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
396 }
397
398 // Measure audio level (0-9)
399 // TODO(henrik.lundin) Use the |muted| information here too.
400 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
401 // https://crbug.com/webrtc/7517).
402 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
403
404 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
405 // The first frame with a valid rtp timestamp.
406 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
407 }
408
409 if (capture_start_rtp_time_stamp_ >= 0) {
410 // audio_frame.timestamp_ should be valid from now on.
411
412 // Compute elapsed time.
413 int64_t unwrap_timestamp =
414 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
415 audio_frame->elapsed_time_ms_ =
416 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
417 (GetRtpTimestampRateHz() / 1000);
418
419 {
420 rtc::CritScope lock(&ts_stats_lock_);
421 // Compute ntp time.
422 audio_frame->ntp_time_ms_ =
423 ntp_estimator_.Estimate(audio_frame->timestamp_);
424 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
425 if (audio_frame->ntp_time_ms_ > 0) {
426 // Compute |capture_start_ntp_time_ms_| so that
427 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
428 capture_start_ntp_time_ms_ =
429 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
430 }
431 }
432 }
433
434 {
435 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200436 acm_receiver_.TargetDelayMs());
437 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200438 rtc::CritScope lock(&video_sync_lock_);
439 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
440 jitter_buffer_delay + playout_delay_ms_);
441 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
442 jitter_buffer_delay);
443 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
444 playout_delay_ms_);
445 }
446
447 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
448 : AudioMixer::Source::AudioFrameInfo::kNormal;
449}
450
451int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100452 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200453 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200454 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
455 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200456}
457
458ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100459 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200460 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100461 NetEqFactory* neteq_factory,
Niels Möller530ead42018-10-04 14:28:39 +0200462 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700463 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200464 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200465 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200466 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200467 uint32_t remote_ssrc,
468 size_t jitter_buffer_max_packets,
469 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100470 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100471 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200472 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700473 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700474 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700475 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200476 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100477 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200478 remote_ssrc_(remote_ssrc),
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100479 acm_receiver_(AcmConfig(neteq_factory,
480 decoder_factory,
Niels Möllered44f542019-07-30 15:15:59 +0200481 codec_pair_id,
482 jitter_buffer_max_packets,
483 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200484 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100485 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200486 playout_timestamp_rtp_(0),
487 playout_delay_ms_(0),
488 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
489 capture_start_rtp_time_stamp_(-1),
490 capture_start_ntp_time_ms_(-1),
491 _moduleProcessThreadPtr(module_process_thread),
492 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200493 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700494 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700495 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700496 frame_decryptor_(frame_decryptor),
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200497 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100498 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200499 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100500
Niels Möller530ead42018-10-04 14:28:39 +0200501 RTC_DCHECK(module_process_thread);
502 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200503
504 acm_receiver_.ResetInitialDelay();
505 acm_receiver_.SetMinimumDelay(0);
506 acm_receiver_.SetMaximumDelay(0);
507 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200508
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200509 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200510
511 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
512 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100513 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200514 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100515 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200516 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200517 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200518 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200519 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200520
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100521 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200522 _rtpRtcpModule->SetSendingMediaStatus(false);
523 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200524
Niels Möller530ead42018-10-04 14:28:39 +0200525 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
526
Niels Möllerb6220d92019-08-29 13:47:09 +0200527 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200528 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200529
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700530 if (media_transport()) {
531 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200532 }
Niels Möller530ead42018-10-04 14:28:39 +0200533}
534
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100535ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200536 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200537
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700538 if (media_transport()) {
539 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200540 }
541
Niels Möller530ead42018-10-04 14:28:39 +0200542 StopPlayout();
543
Niels Möller530ead42018-10-04 14:28:39 +0200544 if (_moduleProcessThreadPtr)
545 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200546}
547
548void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200549 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200550 rtc::CritScope cs(&_callbackCritSect);
551 audio_sink_ = sink;
552}
553
Niels Möller80c67622018-11-12 13:22:47 +0100554void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200555 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100556 rtc::CritScope lock(&playing_lock_);
557 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200558}
559
Niels Möller80c67622018-11-12 13:22:47 +0100560void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200561 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100562 rtc::CritScope lock(&playing_lock_);
563 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200564 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200565}
566
Jonas Olssona4d87372019-07-05 19:08:33 +0200567absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
568 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200569 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200570 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200571}
572
Niels Möller530ead42018-10-04 14:28:39 +0200573void ChannelReceive::SetReceiveCodecs(
574 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200575 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200576 for (const auto& kv : codecs) {
577 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
578 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
579 }
Niels Möllered44f542019-07-30 15:15:59 +0200580 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200581}
582
Niels Möller349ade32018-11-16 09:50:42 +0100583// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200584void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
585 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200586
587 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000588 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200589 last_received_rtp_timestamp_ = packet.Timestamp();
590 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200591 }
592
593 // Store playout timestamp for the received RTP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200594 UpdatePlayoutTimestamp(false, now_ms);
Niels Möller530ead42018-10-04 14:28:39 +0200595
596 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
597 if (it == payload_type_frequencies_.end())
598 return;
599 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
600 RtpPacketReceived packet_copy(packet);
601 packet_copy.set_payload_type_frequency(it->second);
602
603 rtp_receive_statistics_->OnRtpPacket(packet_copy);
604
605 RTPHeader header;
606 packet_copy.GetHeader(&header);
607
608 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
609}
610
Niels Möllered44f542019-07-30 15:15:59 +0200611void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200612 size_t packet_length,
613 const RTPHeader& header) {
614 const uint8_t* payload = packet + header.headerLength;
615 assert(packet_length >= header.headerLength);
616 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200617
Benjamin Wright84583f62018-10-04 14:22:34 -0700618 size_t payload_data_length = payload_length - header.paddingLength;
619
620 // E2EE Custom Audio Frame Decryption (This is optional).
621 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
622 rtc::Buffer decrypted_audio_payload;
623 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000624 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700625 cricket::MEDIA_TYPE_AUDIO, payload_length);
626 decrypted_audio_payload.SetSize(max_plaintext_size);
627
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000628 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
629 header.arrOfCSRCs + header.numCSRCs);
630 const FrameDecryptorInterface::Result decrypt_result =
631 frame_decryptor_->Decrypt(
632 cricket::MEDIA_TYPE_AUDIO, csrcs,
633 /*additional_data=*/nullptr,
634 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
635 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700636
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000637 if (decrypt_result.IsOk()) {
638 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
639 } else {
640 // Interpret failures as a silent frame.
641 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700642 }
643
Benjamin Wright84583f62018-10-04 14:22:34 -0700644 payload = decrypted_audio_payload.data();
645 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700646 } else if (crypto_options_.sframe.require_frame_encryption) {
647 RTC_DLOG(LS_ERROR)
648 << "FrameDecryptor required but not set, dropping packet";
649 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700650 }
651
Niels Möllered44f542019-07-30 15:15:59 +0200652 OnReceivedPayloadData(
653 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200654}
655
Niels Möller349ade32018-11-16 09:50:42 +0100656// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100657void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200658 // Store playout timestamp for the received RTCP packet
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200659 UpdatePlayoutTimestamp(true, rtc::TimeMillis());
Niels Möller530ead42018-10-04 14:28:39 +0200660
661 // Deliver RTCP packet to RTP/RTCP module for parsing
662 _rtpRtcpModule->IncomingRtcpPacket(data, length);
663
664 int64_t rtt = GetRTT();
665 if (rtt == 0) {
666 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100667 return;
Niels Möller530ead42018-10-04 14:28:39 +0200668 }
669
Niels Möller530ead42018-10-04 14:28:39 +0200670 uint32_t ntp_secs = 0;
671 uint32_t ntp_frac = 0;
672 uint32_t rtp_timestamp = 0;
673 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
674 &rtp_timestamp)) {
675 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100676 return;
Niels Möller530ead42018-10-04 14:28:39 +0200677 }
678
679 {
680 rtc::CritScope lock(&ts_stats_lock_);
681 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
682 }
Niels Möller530ead42018-10-04 14:28:39 +0200683}
684
685int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200686 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200687 return _outputAudioLevel.LevelFullRange();
688}
689
690double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200691 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200692 return _outputAudioLevel.TotalEnergy();
693}
694
695double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200696 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200697 return _outputAudioLevel.TotalDuration();
698}
699
700void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200701 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200702 rtc::CritScope cs(&volume_settings_critsect_);
703 _outputGain = scaling;
704}
705
Niels Möller530ead42018-10-04 14:28:39 +0200706void ChannelReceive::RegisterReceiverCongestionControlObjects(
707 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200708 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200709 RTC_DCHECK(packet_router);
710 RTC_DCHECK(!packet_router_);
711 constexpr bool remb_candidate = false;
712 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
713 packet_router_ = packet_router;
714}
715
716void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200717 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200718 RTC_DCHECK(packet_router_);
719 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
720 packet_router_ = nullptr;
721}
722
Niels Möller349ade32018-11-16 09:50:42 +0100723CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200724 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200725 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100726 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200727
728 // The jitter statistics is updated for each received RTP packet and is
729 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200730 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200731 StreamStatistician* statistician =
732 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
733 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200734 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200735 }
736
Niels Möllerd77cc242019-08-22 09:40:25 +0200737 stats.cumulativeLost = rtp_stats.packets_lost;
738 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200739
740 // --- RTT
741 stats.rttMs = GetRTT();
742
743 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200744 if (statistician) {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200745 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
746
747 stats.header_and_padding_bytes_rcvd =
748 rtp_stats.packet_counter.header_bytes +
749 rtp_stats.packet_counter.padding_bytes;
Niels Möllerd77cc242019-08-22 09:40:25 +0200750 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200751 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200752 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200753 } else {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200754 stats.payload_bytes_rcvd = 0;
755 stats.header_and_padding_bytes_rcvd = 0;
Henrik Boström01738c62019-04-15 17:32:00 +0200756 stats.packetsReceived = 0;
757 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200758 }
759
Niels Möller530ead42018-10-04 14:28:39 +0200760 // --- Timestamps
761 {
762 rtc::CritScope lock(&ts_stats_lock_);
763 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
764 }
Niels Möller80c67622018-11-12 13:22:47 +0100765 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200766}
767
Niels Möller349ade32018-11-16 09:50:42 +0100768void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200769 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200770 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100771 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200772 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
773 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100774 } else {
775 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200776 kDefaultMaxReorderingThreshold);
777 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100778 }
Niels Möller530ead42018-10-04 14:28:39 +0200779}
780
781// Called when we are missing one or more packets.
782int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
783 int length) {
784 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
785}
786
Niels Möllerdced9f62018-11-19 10:27:07 +0100787void ChannelReceive::SetAssociatedSendChannel(
788 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200789 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200790 rtc::CritScope lock(&assoc_send_channel_lock_);
791 associated_send_channel_ = channel;
792}
793
Niels Möller80c67622018-11-12 13:22:47 +0100794NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200795 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100796 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200797 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100798 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200799}
800
Niels Möller80c67622018-11-12 13:22:47 +0100801AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200802 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100803 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200804 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100805 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200806}
807
808uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200809 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
810 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200811 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200812 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200813}
814
Niels Möller349ade32018-11-16 09:50:42 +0100815void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200816 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100817 // Limit to range accepted by both VoE and ACM, so we're at least getting as
818 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100819 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
820 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200821 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200822 RTC_DLOG(LS_ERROR)
823 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200824 }
Niels Möller530ead42018-10-04 14:28:39 +0200825}
826
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200827bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
828 int64_t* time_ms) const {
Niels Möller349ade32018-11-16 09:50:42 +0100829 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200830 {
831 rtc::CritScope lock(&video_sync_lock_);
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200832 if (!playout_timestamp_rtp_time_ms_)
833 return false;
834 *rtp_timestamp = playout_timestamp_rtp_;
835 *time_ms = playout_timestamp_rtp_time_ms_.value();
836 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200837 }
Niels Möller530ead42018-10-04 14:28:39 +0200838}
839
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200840void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
841 int64_t time_ms) {
842 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
843 rtc::CritScope lock(&video_sync_lock_);
844 playout_timestamp_ntp_ = ntp_timestamp_ms;
845 playout_timestamp_ntp_time_ms_ = time_ms;
846}
847
848absl::optional<int64_t>
849ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const {
850 RTC_DCHECK(worker_thread_checker_.IsCurrent());
851 rtc::CritScope lock(&video_sync_lock_);
852 if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_)
853 return absl::nullopt;
854
855 int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_;
856 return *playout_timestamp_ntp_ + elapsed_ms;
857}
858
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100859bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200860 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100861}
862
863int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200864 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100865}
866
Niels Möller530ead42018-10-04 14:28:39 +0200867absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200868 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200869 Syncable::Info info;
870 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
871 &info.capture_time_ntp_frac, nullptr, nullptr,
872 &info.capture_time_source_clock) != 0) {
873 return absl::nullopt;
874 }
875 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000876 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200877 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
878 return absl::nullopt;
879 }
880 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
881 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
882 }
883 return info;
884}
885
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200886void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200887 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200888
889 if (!jitter_buffer_playout_timestamp_) {
890 // This can happen if this channel has not received any RTP packets. In
891 // this case, NetEq is not capable of computing a playout timestamp.
892 return;
893 }
894
895 uint16_t delay_ms = 0;
896 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
897 RTC_DLOG(LS_WARNING)
898 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
899 << " playout delay from the ADM";
900 return;
901 }
902
903 RTC_DCHECK(jitter_buffer_playout_timestamp_);
904 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
905
906 // Remove the playout delay.
907 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
908
909 {
910 rtc::CritScope lock(&video_sync_lock_);
911 if (!rtcp) {
912 playout_timestamp_rtp_ = playout_timestamp;
Åsa Perssonfcf79cc2019-10-22 15:23:44 +0200913 playout_timestamp_rtp_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200914 }
915 playout_delay_ms_ = delay_ms;
916 }
917}
918
919int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200920 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200921 // Default to the playout frequency if we've not gotten any packets yet.
922 // TODO(ossu): Zero clockrate can only happen if we've added an external
923 // decoder for a format we don't support internally. Remove once that way of
924 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +0200925 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
926 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
927 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100928 return (decoder && decoder->second.clockrate_hz != 0)
929 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200930 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200931}
932
933int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700934 if (media_transport()) {
935 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800936 if (target_rate.has_value()) {
937 return target_rate->network_estimate.round_trip_time.ms();
938 }
939
940 return 0;
941 }
Niels Möller530ead42018-10-04 14:28:39 +0200942 std::vector<RTCPReportBlock> report_blocks;
943 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
944
945 // TODO(nisse): Could we check the return value from the ->RTT() call below,
946 // instead of checking if we have any report blocks?
947 if (report_blocks.empty()) {
948 rtc::CritScope lock(&assoc_send_channel_lock_);
949 // Tries to get RTT from an associated channel.
950 if (!associated_send_channel_) {
951 return 0;
952 }
953 return associated_send_channel_->GetRTT();
954 }
955
956 int64_t rtt = 0;
957 int64_t avg_rtt = 0;
958 int64_t max_rtt = 0;
959 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100960 // TODO(nisse): This method computes RTT based on sender reports, even though
961 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200962 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
963 0) {
964 return 0;
965 }
966 return rtt;
967}
968
Niels Möller349ade32018-11-16 09:50:42 +0100969} // namespace
970
971std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100972 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100973 ProcessThread* module_process_thread,
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100974 NetEqFactory* neteq_factory,
Niels Möller349ade32018-11-16 09:50:42 +0100975 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700976 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100977 Transport* rtcp_send_transport,
978 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200979 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100980 uint32_t remote_ssrc,
981 size_t jitter_buffer_max_packets,
982 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100983 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100984 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100985 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
986 absl::optional<AudioCodecPairId> codec_pair_id,
987 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
988 const webrtc::CryptoOptions& crypto_options) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200989 return std::make_unique<ChannelReceive>(
Ivo Creusenc3d1f9b2019-11-01 11:47:51 +0100990 clock, module_process_thread, neteq_factory, audio_device_module,
991 media_transport_config, rtcp_send_transport, rtc_event_log, local_ssrc,
992 remote_ssrc, jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100993 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
994 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100995}
996
Niels Möller530ead42018-10-04 14:28:39 +0200997} // namespace voe
998} // namespace webrtc