blob: 486dcb11ac5efbb2aa5271e8b4ebe13aeb3810d3 [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"
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070046#include "system_wrappers/include/field_trial.h"
Niels Möller530ead42018-10-04 14:28:39 +020047#include "system_wrappers/include/metrics.h"
48
49namespace webrtc {
50namespace voe {
51
52namespace {
53
54constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020055
56// Video Sync.
57constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
58constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
59
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070060// Field trial which controls whether to report standard-compliant bytes
61// sent/received per stream. If enabled, padding and headers are not included
62// in bytes sent or received.
63constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats";
64
Niels Möllerafb5dbb2019-02-15 15:21:47 +010065RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000066 const MediaTransportEncodedAudioFrame& frame,
67 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010068 webrtc::RTPHeader rtp_header;
69 rtp_header.payloadType = frame.payload_type();
70 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
71 rtp_header.timestamp = frame.starting_sample_index();
72 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020073
Sergey Silkine049eba2019-02-18 09:52:26 +000074 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020075
76 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010077 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020078}
79
Niels Möllered44f542019-07-30 15:15:59 +020080AudioCodingModule::Config AcmConfig(
81 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
82 absl::optional<AudioCodecPairId> codec_pair_id,
83 size_t jitter_buffer_max_packets,
84 bool jitter_buffer_fast_playout) {
85 AudioCodingModule::Config acm_config;
86 acm_config.decoder_factory = decoder_factory;
87 acm_config.neteq_config.codec_pair_id = codec_pair_id;
88 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
89 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
90 acm_config.neteq_config.enable_muted_state = true;
91
92 return acm_config;
93}
94
Niels Möller349ade32018-11-16 09:50:42 +010095class ChannelReceive : public ChannelReceiveInterface,
96 public MediaTransportAudioSinkInterface {
97 public:
98 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010099 ChannelReceive(Clock* clock,
100 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +0100101 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700102 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100103 Transport* rtcp_send_transport,
104 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200105 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100106 uint32_t remote_ssrc,
107 size_t jitter_buffer_max_packets,
108 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100109 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100110 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100111 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
112 absl::optional<AudioCodecPairId> codec_pair_id,
113 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
114 const webrtc::CryptoOptions& crypto_options);
115 ~ChannelReceive() override;
116
117 void SetSink(AudioSinkInterface* sink) override;
118
119 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
120
121 // API methods
122
123 void StartPlayout() override;
124 void StopPlayout() override;
125
126 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000127 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
128 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100129
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100130 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100131
132 // RtpPacketSinkInterface.
133 void OnRtpPacket(const RtpPacketReceived& packet) override;
134
135 // Muting, Volume and Level.
136 void SetChannelOutputVolumeScaling(float scaling) override;
137 int GetSpeechOutputLevelFullRange() const override;
138 // See description of "totalAudioEnergy" in the WebRTC stats spec:
139 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
140 double GetTotalOutputEnergy() const override;
141 double GetTotalOutputDuration() const override;
142
143 // Stats.
144 NetworkStatistics GetNetworkStatistics() const override;
145 AudioDecodingCallStats GetDecodingCallStatistics() const override;
146
147 // Audio+Video Sync.
148 uint32_t GetDelayEstimate() const override;
149 void SetMinimumPlayoutDelay(int delayMs) override;
150 uint32_t GetPlayoutTimestamp() const override;
151
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100152 // Audio quality.
153 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
154 int GetBaseMinimumPlayoutDelayMs() const override;
155
Niels Möller349ade32018-11-16 09:50:42 +0100156 // Produces the transport-related timestamps; current_delay_ms is left unset.
157 absl::optional<Syncable::Info> GetSyncInfo() const override;
158
Niels Möller349ade32018-11-16 09:50:42 +0100159 void RegisterReceiverCongestionControlObjects(
160 PacketRouter* packet_router) override;
161 void ResetReceiverCongestionControlObjects() override;
162
163 CallReceiveStatistics GetRTCPStatistics() const override;
164 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
165
166 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
167 int sample_rate_hz,
168 AudioFrame* audio_frame) override;
169
170 int PreferredSampleRate() const override;
171
172 // Associate to a send channel.
173 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100174 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100175
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700176 // TODO(sukhanov): Return const pointer. It requires making media transport
177 // getters like GetLatestTargetTransferRate to be also const.
178 MediaTransportInterface* media_transport() const {
179 return media_transport_config_.media_transport;
180 }
181
Niels Möller349ade32018-11-16 09:50:42 +0100182 private:
Niels Möllered44f542019-07-30 15:15:59 +0200183 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100184 size_t packet_length,
185 const RTPHeader& header);
186 int ResendPackets(const uint16_t* sequence_numbers, int length);
187 void UpdatePlayoutTimestamp(bool rtcp);
188
189 int GetRtpTimestampRateHz() const;
190 int64_t GetRTT() const;
191
192 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000193 void OnData(uint64_t channel_id,
194 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100195
Niels Möllered44f542019-07-30 15:15:59 +0200196 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
197 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100198
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100199 bool Playing() const {
200 rtc::CritScope lock(&playing_lock_);
201 return playing_;
202 }
203
Niels Möller349ade32018-11-16 09:50:42 +0100204 // Thread checkers document and lock usage of some methods to specific threads
205 // we know about. The goal is to eventually split up voe::ChannelReceive into
206 // parts with single-threaded semantics, and thereby reduce the need for
207 // locks.
208 rtc::ThreadChecker worker_thread_checker_;
209 rtc::ThreadChecker module_process_thread_checker_;
210 // Methods accessed from audio and video threads are checked for sequential-
211 // only access. We don't necessarily own and control these threads, so thread
212 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
213 // audio thread to another, but access is still sequential.
214 rtc::RaceChecker audio_thread_race_checker_;
215 rtc::RaceChecker video_capture_thread_race_checker_;
216 rtc::CriticalSection _callbackCritSect;
217 rtc::CriticalSection volume_settings_critsect_;
218
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100219 rtc::CriticalSection playing_lock_;
220 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100221
222 RtcEventLog* const event_log_;
223
224 // Indexed by payload type.
225 std::map<uint8_t, int> payload_type_frequencies_;
226
227 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
228 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
229 const uint32_t remote_ssrc_;
230
Chen Xing054e3bb2019-08-02 10:29:26 +0000231 // Info for GetSyncInfo is updated on network or worker thread, and queried on
232 // the worker thread.
233 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100234 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000235 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100236 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000237 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100238
Niels Möllered44f542019-07-30 15:15:59 +0200239 // The AcmReceiver is thread safe, using its own lock.
240 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100241 AudioSinkInterface* audio_sink_ = nullptr;
242 AudioLevel _outputAudioLevel;
243
244 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
245
246 // Timestamp of the audio pulled from NetEq.
247 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
248
249 rtc::CriticalSection video_sync_lock_;
250 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
251 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
252
253 rtc::CriticalSection ts_stats_lock_;
254
255 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
256 // The rtp timestamp of the first played out audio frame.
257 int64_t capture_start_rtp_time_stamp_;
258 // The capture ntp time (in local timebase) of the first played out audio
259 // frame.
260 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
261
262 // uses
263 ProcessThread* _moduleProcessThreadPtr;
264 AudioDeviceModule* _audioDeviceModulePtr;
265 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
266
267 // An associated send channel.
268 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100269 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100270 RTC_GUARDED_BY(assoc_send_channel_lock_);
271
272 PacketRouter* packet_router_ = nullptr;
273
274 rtc::ThreadChecker construction_thread_;
275
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700276 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100277
278 // E2EE Audio Frame Decryption
279 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
280 webrtc::CryptoOptions crypto_options_;
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700281
282 const bool use_standard_bytes_stats_;
Niels Möller349ade32018-11-16 09:50:42 +0100283};
Niels Möller530ead42018-10-04 14:28:39 +0200284
Niels Möllered44f542019-07-30 15:15:59 +0200285void ChannelReceive::OnReceivedPayloadData(
286 rtc::ArrayView<const uint8_t> payload,
287 const RTPHeader& rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200288 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700289 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200290
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100291 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200292 // Avoid inserting into NetEQ when we are not playing. Count the
293 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200294 return;
Niels Möller530ead42018-10-04 14:28:39 +0200295 }
296
297 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200298 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200299 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
300 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200301 return;
Niels Möller530ead42018-10-04 14:28:39 +0200302 }
303
304 int64_t round_trip_time = 0;
305 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
306
Niels Möllered44f542019-07-30 15:15:59 +0200307 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200308 if (!nack_list.empty()) {
309 // Can't use nack_list.data() since it's not supported by all
310 // compilers.
311 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
312 }
Niels Möller530ead42018-10-04 14:28:39 +0200313}
314
Niels Möller7d76a312018-10-26 12:57:07 +0200315// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000316void ChannelReceive::OnData(uint64_t channel_id,
317 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700318 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200319
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100320 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200321 // Avoid inserting into NetEQ when we are not playing. Count the
322 // packet as discarded.
323 return;
324 }
325
326 // Send encoded audio frame to Decoder / NetEq.
Niels Möllered44f542019-07-30 15:15:59 +0200327 if (acm_receiver_.InsertPacket(
328 CreateRTPHeaderForMediaTransportFrame(frame, channel_id),
329 frame.encoded_data()) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200330 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
331 "push data to the ACM";
332 }
333}
334
Niels Möller530ead42018-10-04 14:28:39 +0200335AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
336 int sample_rate_hz,
337 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100338 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200339 audio_frame->sample_rate_hz_ = sample_rate_hz;
340
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200341 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100342
Niels Möller530ead42018-10-04 14:28:39 +0200343 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
344 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200345 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
346 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200347 RTC_DLOG(LS_ERROR)
348 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
349 // In all likelihood, the audio in this frame is garbage. We return an
350 // error so that the audio mixer module doesn't add it to the mix. As
351 // a result, it won't be played out and the actions skipped here are
352 // irrelevant.
353 return AudioMixer::Source::AudioFrameInfo::kError;
354 }
355
356 if (muted) {
357 // TODO(henrik.lundin): We should be able to do better than this. But we
358 // will have to go through all the cases below where the audio samples may
359 // be used, and handle the muted case in some way.
360 AudioFrameOperations::Mute(audio_frame);
361 }
362
363 {
364 // Pass the audio buffers to an optional sink callback, before applying
365 // scaling/panning, as that applies to the mix operation.
366 // External recipients of the audio (e.g. via AudioTrack), will do their
367 // own mixing/dynamic processing.
368 rtc::CritScope cs(&_callbackCritSect);
369 if (audio_sink_) {
370 AudioSinkInterface::Data data(
371 audio_frame->data(), audio_frame->samples_per_channel_,
372 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
373 audio_frame->timestamp_);
374 audio_sink_->OnData(data);
375 }
376 }
377
378 float output_gain = 1.0f;
379 {
380 rtc::CritScope cs(&volume_settings_critsect_);
381 output_gain = _outputGain;
382 }
383
384 // Output volume scaling
385 if (output_gain < 0.99f || output_gain > 1.01f) {
386 // TODO(solenberg): Combine with mute state - this can cause clicks!
387 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
388 }
389
390 // Measure audio level (0-9)
391 // TODO(henrik.lundin) Use the |muted| information here too.
392 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
393 // https://crbug.com/webrtc/7517).
394 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
395
396 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
397 // The first frame with a valid rtp timestamp.
398 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
399 }
400
401 if (capture_start_rtp_time_stamp_ >= 0) {
402 // audio_frame.timestamp_ should be valid from now on.
403
404 // Compute elapsed time.
405 int64_t unwrap_timestamp =
406 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
407 audio_frame->elapsed_time_ms_ =
408 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
409 (GetRtpTimestampRateHz() / 1000);
410
411 {
412 rtc::CritScope lock(&ts_stats_lock_);
413 // Compute ntp time.
414 audio_frame->ntp_time_ms_ =
415 ntp_estimator_.Estimate(audio_frame->timestamp_);
416 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
417 if (audio_frame->ntp_time_ms_ > 0) {
418 // Compute |capture_start_ntp_time_ms_| so that
419 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
420 capture_start_ntp_time_ms_ =
421 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
422 }
423 }
424 }
425
426 {
427 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200428 acm_receiver_.TargetDelayMs());
429 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200430 rtc::CritScope lock(&video_sync_lock_);
431 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
432 jitter_buffer_delay + playout_delay_ms_);
433 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
434 jitter_buffer_delay);
435 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
436 playout_delay_ms_);
437 }
438
439 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
440 : AudioMixer::Source::AudioFrameInfo::kNormal;
441}
442
443int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100444 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200445 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200446 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
447 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200448}
449
450ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100451 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200452 ProcessThread* module_process_thread,
453 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700454 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200455 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200456 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200457 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200458 uint32_t remote_ssrc,
459 size_t jitter_buffer_max_packets,
460 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100461 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100462 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200463 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700464 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700465 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700466 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200467 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100468 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200469 remote_ssrc_(remote_ssrc),
Niels Möllered44f542019-07-30 15:15:59 +0200470 acm_receiver_(AcmConfig(decoder_factory,
471 codec_pair_id,
472 jitter_buffer_max_packets,
473 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200474 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100475 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200476 playout_timestamp_rtp_(0),
477 playout_delay_ms_(0),
478 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
479 capture_start_rtp_time_stamp_(-1),
480 capture_start_ntp_time_ms_(-1),
481 _moduleProcessThreadPtr(module_process_thread),
482 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200483 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700484 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700485 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700486 frame_decryptor_(frame_decryptor),
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700487 crypto_options_(crypto_options),
488 use_standard_bytes_stats_(
489 webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) {
Niels Möller349ade32018-11-16 09:50:42 +0100490 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200491 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100492
Niels Möller530ead42018-10-04 14:28:39 +0200493 RTC_DCHECK(module_process_thread);
494 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200495
496 acm_receiver_.ResetInitialDelay();
497 acm_receiver_.SetMinimumDelay(0);
498 acm_receiver_.SetMaximumDelay(0);
499 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200500
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200501 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200502
503 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
504 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100505 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200506 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100507 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200508 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200509 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200510 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200511 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200512
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100513 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200514 _rtpRtcpModule->SetSendingMediaStatus(false);
515 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200516
Niels Möller530ead42018-10-04 14:28:39 +0200517 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
518
Niels Möllerb6220d92019-08-29 13:47:09 +0200519 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200520 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200521
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700522 if (media_transport()) {
523 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200524 }
Niels Möller530ead42018-10-04 14:28:39 +0200525}
526
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100527ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200528 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200529
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700530 if (media_transport()) {
531 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200532 }
533
Niels Möller530ead42018-10-04 14:28:39 +0200534 StopPlayout();
535
Niels Möller530ead42018-10-04 14:28:39 +0200536 if (_moduleProcessThreadPtr)
537 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200538}
539
540void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200541 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200542 rtc::CritScope cs(&_callbackCritSect);
543 audio_sink_ = sink;
544}
545
Niels Möller80c67622018-11-12 13:22:47 +0100546void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200547 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100548 rtc::CritScope lock(&playing_lock_);
549 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200550}
551
Niels Möller80c67622018-11-12 13:22:47 +0100552void ChannelReceive::StopPlayout() {
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_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200556 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200557}
558
Jonas Olssona4d87372019-07-05 19:08:33 +0200559absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
560 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200561 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200562 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200563}
564
Niels Möller530ead42018-10-04 14:28:39 +0200565void ChannelReceive::SetReceiveCodecs(
566 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200567 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200568 for (const auto& kv : codecs) {
569 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
570 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
571 }
Niels Möllered44f542019-07-30 15:15:59 +0200572 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200573}
574
Niels Möller349ade32018-11-16 09:50:42 +0100575// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200576void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
577 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200578
579 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000580 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200581 last_received_rtp_timestamp_ = packet.Timestamp();
582 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200583 }
584
585 // Store playout timestamp for the received RTP packet
586 UpdatePlayoutTimestamp(false);
587
588 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
589 if (it == payload_type_frequencies_.end())
590 return;
591 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
592 RtpPacketReceived packet_copy(packet);
593 packet_copy.set_payload_type_frequency(it->second);
594
595 rtp_receive_statistics_->OnRtpPacket(packet_copy);
596
597 RTPHeader header;
598 packet_copy.GetHeader(&header);
599
600 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
601}
602
Niels Möllered44f542019-07-30 15:15:59 +0200603void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200604 size_t packet_length,
605 const RTPHeader& header) {
606 const uint8_t* payload = packet + header.headerLength;
607 assert(packet_length >= header.headerLength);
608 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200609
Benjamin Wright84583f62018-10-04 14:22:34 -0700610 size_t payload_data_length = payload_length - header.paddingLength;
611
612 // E2EE Custom Audio Frame Decryption (This is optional).
613 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
614 rtc::Buffer decrypted_audio_payload;
615 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000616 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700617 cricket::MEDIA_TYPE_AUDIO, payload_length);
618 decrypted_audio_payload.SetSize(max_plaintext_size);
619
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000620 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
621 header.arrOfCSRCs + header.numCSRCs);
622 const FrameDecryptorInterface::Result decrypt_result =
623 frame_decryptor_->Decrypt(
624 cricket::MEDIA_TYPE_AUDIO, csrcs,
625 /*additional_data=*/nullptr,
626 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
627 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700628
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000629 if (decrypt_result.IsOk()) {
630 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
631 } else {
632 // Interpret failures as a silent frame.
633 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700634 }
635
Benjamin Wright84583f62018-10-04 14:22:34 -0700636 payload = decrypted_audio_payload.data();
637 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700638 } else if (crypto_options_.sframe.require_frame_encryption) {
639 RTC_DLOG(LS_ERROR)
640 << "FrameDecryptor required but not set, dropping packet";
641 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700642 }
643
Niels Möllered44f542019-07-30 15:15:59 +0200644 OnReceivedPayloadData(
645 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200646}
647
Niels Möller349ade32018-11-16 09:50:42 +0100648// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100649void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200650 // Store playout timestamp for the received RTCP packet
651 UpdatePlayoutTimestamp(true);
652
653 // Deliver RTCP packet to RTP/RTCP module for parsing
654 _rtpRtcpModule->IncomingRtcpPacket(data, length);
655
656 int64_t rtt = GetRTT();
657 if (rtt == 0) {
658 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100659 return;
Niels Möller530ead42018-10-04 14:28:39 +0200660 }
661
Niels Möller530ead42018-10-04 14:28:39 +0200662 uint32_t ntp_secs = 0;
663 uint32_t ntp_frac = 0;
664 uint32_t rtp_timestamp = 0;
665 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
666 &rtp_timestamp)) {
667 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100668 return;
Niels Möller530ead42018-10-04 14:28:39 +0200669 }
670
671 {
672 rtc::CritScope lock(&ts_stats_lock_);
673 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
674 }
Niels Möller530ead42018-10-04 14:28:39 +0200675}
676
677int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200678 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200679 return _outputAudioLevel.LevelFullRange();
680}
681
682double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200683 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200684 return _outputAudioLevel.TotalEnergy();
685}
686
687double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200688 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200689 return _outputAudioLevel.TotalDuration();
690}
691
692void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200693 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200694 rtc::CritScope cs(&volume_settings_critsect_);
695 _outputGain = scaling;
696}
697
Niels Möller530ead42018-10-04 14:28:39 +0200698void ChannelReceive::RegisterReceiverCongestionControlObjects(
699 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200700 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200701 RTC_DCHECK(packet_router);
702 RTC_DCHECK(!packet_router_);
703 constexpr bool remb_candidate = false;
704 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
705 packet_router_ = packet_router;
706}
707
708void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200709 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200710 RTC_DCHECK(packet_router_);
711 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
712 packet_router_ = nullptr;
713}
714
Niels Möller349ade32018-11-16 09:50:42 +0100715CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200716 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200717 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100718 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200719
720 // The jitter statistics is updated for each received RTP packet and is
721 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200722 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200723 StreamStatistician* statistician =
724 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
725 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200726 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200727 }
728
Niels Möllerd77cc242019-08-22 09:40:25 +0200729 stats.cumulativeLost = rtp_stats.packets_lost;
730 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200731
732 // --- RTT
733 stats.rttMs = GetRTT();
734
735 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200736 if (statistician) {
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700737 if (use_standard_bytes_stats_) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200738 stats.bytesReceived = rtp_stats.packet_counter.payload_bytes;
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700739 } else {
Niels Möllerd77cc242019-08-22 09:40:25 +0200740 stats.bytesReceived = rtp_stats.packet_counter.TotalBytes();
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700741 }
Niels Möllerd77cc242019-08-22 09:40:25 +0200742 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200743 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200744 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200745 } else {
746 stats.bytesReceived = 0;
747 stats.packetsReceived = 0;
748 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200749 }
750
Niels Möller530ead42018-10-04 14:28:39 +0200751 // --- Timestamps
752 {
753 rtc::CritScope lock(&ts_stats_lock_);
754 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
755 }
Niels Möller80c67622018-11-12 13:22:47 +0100756 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200757}
758
Niels Möller349ade32018-11-16 09:50:42 +0100759void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200760 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200761 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100762 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200763 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
764 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100765 } else {
766 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200767 kDefaultMaxReorderingThreshold);
768 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100769 }
Niels Möller530ead42018-10-04 14:28:39 +0200770}
771
772// Called when we are missing one or more packets.
773int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
774 int length) {
775 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
776}
777
Niels Möllerdced9f62018-11-19 10:27:07 +0100778void ChannelReceive::SetAssociatedSendChannel(
779 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200780 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200781 rtc::CritScope lock(&assoc_send_channel_lock_);
782 associated_send_channel_ = channel;
783}
784
Niels Möller80c67622018-11-12 13:22:47 +0100785NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200786 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100787 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200788 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100789 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200790}
791
Niels Möller80c67622018-11-12 13:22:47 +0100792AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200793 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100794 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200795 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100796 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200797}
798
799uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200800 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
801 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200802 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200803 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200804}
805
Niels Möller349ade32018-11-16 09:50:42 +0100806void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200807 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100808 // Limit to range accepted by both VoE and ACM, so we're at least getting as
809 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100810 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
811 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200812 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200813 RTC_DLOG(LS_ERROR)
814 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200815 }
Niels Möller530ead42018-10-04 14:28:39 +0200816}
817
Niels Möller349ade32018-11-16 09:50:42 +0100818uint32_t ChannelReceive::GetPlayoutTimestamp() const {
819 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200820 {
821 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100822 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200823 }
Niels Möller530ead42018-10-04 14:28:39 +0200824}
825
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100826bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200827 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100828}
829
830int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200831 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100832}
833
Niels Möller530ead42018-10-04 14:28:39 +0200834absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200835 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200836 Syncable::Info info;
837 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
838 &info.capture_time_ntp_frac, nullptr, nullptr,
839 &info.capture_time_source_clock) != 0) {
840 return absl::nullopt;
841 }
842 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000843 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200844 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
845 return absl::nullopt;
846 }
847 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
848 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
849 }
850 return info;
851}
852
853void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
Niels Möllered44f542019-07-30 15:15:59 +0200854 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200855
856 if (!jitter_buffer_playout_timestamp_) {
857 // This can happen if this channel has not received any RTP packets. In
858 // this case, NetEq is not capable of computing a playout timestamp.
859 return;
860 }
861
862 uint16_t delay_ms = 0;
863 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
864 RTC_DLOG(LS_WARNING)
865 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
866 << " playout delay from the ADM";
867 return;
868 }
869
870 RTC_DCHECK(jitter_buffer_playout_timestamp_);
871 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
872
873 // Remove the playout delay.
874 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
875
876 {
877 rtc::CritScope lock(&video_sync_lock_);
878 if (!rtcp) {
879 playout_timestamp_rtp_ = playout_timestamp;
880 }
881 playout_delay_ms_ = delay_ms;
882 }
883}
884
885int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200886 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200887 // Default to the playout frequency if we've not gotten any packets yet.
888 // TODO(ossu): Zero clockrate can only happen if we've added an external
889 // decoder for a format we don't support internally. Remove once that way of
890 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +0200891 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
892 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
893 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100894 return (decoder && decoder->second.clockrate_hz != 0)
895 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200896 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200897}
898
899int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700900 if (media_transport()) {
901 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800902 if (target_rate.has_value()) {
903 return target_rate->network_estimate.round_trip_time.ms();
904 }
905
906 return 0;
907 }
Niels Möller530ead42018-10-04 14:28:39 +0200908 std::vector<RTCPReportBlock> report_blocks;
909 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
910
911 // TODO(nisse): Could we check the return value from the ->RTT() call below,
912 // instead of checking if we have any report blocks?
913 if (report_blocks.empty()) {
914 rtc::CritScope lock(&assoc_send_channel_lock_);
915 // Tries to get RTT from an associated channel.
916 if (!associated_send_channel_) {
917 return 0;
918 }
919 return associated_send_channel_->GetRTT();
920 }
921
922 int64_t rtt = 0;
923 int64_t avg_rtt = 0;
924 int64_t max_rtt = 0;
925 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100926 // TODO(nisse): This method computes RTT based on sender reports, even though
927 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200928 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
929 0) {
930 return 0;
931 }
932 return rtt;
933}
934
Niels Möller349ade32018-11-16 09:50:42 +0100935} // namespace
936
937std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100938 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100939 ProcessThread* module_process_thread,
940 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700941 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100942 Transport* rtcp_send_transport,
943 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200944 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100945 uint32_t remote_ssrc,
946 size_t jitter_buffer_max_packets,
947 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100948 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100949 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100950 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
951 absl::optional<AudioCodecPairId> codec_pair_id,
952 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
953 const webrtc::CryptoOptions& crypto_options) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200954 return std::make_unique<ChannelReceive>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700955 clock, module_process_thread, audio_device_module, media_transport_config,
Erik Språng70efdde2019-08-21 13:36:20 +0200956 rtcp_send_transport, rtc_event_log, local_ssrc, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100957 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100958 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
959 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100960}
961
Niels Möller530ead42018-10-04 14:28:39 +0200962} // namespace voe
963} // namespace webrtc