blob: 603a52f79169ec7909c4c3d9c23287ecbe52eb55 [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
20#include "absl/memory/memory.h"
Niels Möllera8370302019-09-02 15:16:49 +020021#include "api/crypto/frame_decryptor_interface.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020022#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller349ade32018-11-16 09:50:42 +010023#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020024#include "audio/channel_send.h"
25#include "audio/utility/audio_frame_operations.h"
26#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möllered44f542019-07-30 15:15:59 +020027#include "modules/audio_coding/acm2/acm_receiver.h"
Niels Möller530ead42018-10-04 14:28:39 +020028#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
29#include "modules/audio_device/include/audio_device.h"
30#include "modules/pacing/packet_router.h"
31#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010032#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
33#include "modules/rtp_rtcp/include/rtp_rtcp.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020035#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010036#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020037#include "modules/utility/include/process_thread.h"
38#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020040#include "rtc_base/format_macros.h"
41#include "rtc_base/location.h"
42#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010043#include "rtc_base/numerics/safe_minmax.h"
44#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020045#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/time_utils.h"
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070047#include "system_wrappers/include/field_trial.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
Bjorn A Mellemda4f0932019-07-30 08:34:03 -070061// Field trial which controls whether to report standard-compliant bytes
62// sent/received per stream. If enabled, padding and headers are not included
63// in bytes sent or received.
64constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats";
65
Niels Möllerafb5dbb2019-02-15 15:21:47 +010066RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000067 const MediaTransportEncodedAudioFrame& frame,
68 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010069 webrtc::RTPHeader rtp_header;
70 rtp_header.payloadType = frame.payload_type();
71 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
72 rtp_header.timestamp = frame.starting_sample_index();
73 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020074
Sergey Silkine049eba2019-02-18 09:52:26 +000075 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020076
77 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010078 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020079}
80
Niels Möllered44f542019-07-30 15:15:59 +020081AudioCodingModule::Config AcmConfig(
82 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
83 absl::optional<AudioCodecPairId> codec_pair_id,
84 size_t jitter_buffer_max_packets,
85 bool jitter_buffer_fast_playout) {
86 AudioCodingModule::Config acm_config;
87 acm_config.decoder_factory = decoder_factory;
88 acm_config.neteq_config.codec_pair_id = codec_pair_id;
89 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
90 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
91 acm_config.neteq_config.enable_muted_state = true;
92
93 return acm_config;
94}
95
Niels Möller349ade32018-11-16 09:50:42 +010096class ChannelReceive : public ChannelReceiveInterface,
97 public MediaTransportAudioSinkInterface {
98 public:
99 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +0100100 ChannelReceive(Clock* clock,
101 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +0100102 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700103 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100104 Transport* rtcp_send_transport,
105 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200106 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100107 uint32_t remote_ssrc,
108 size_t jitter_buffer_max_packets,
109 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100110 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100111 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100112 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
113 absl::optional<AudioCodecPairId> codec_pair_id,
114 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
115 const webrtc::CryptoOptions& crypto_options);
116 ~ChannelReceive() override;
117
118 void SetSink(AudioSinkInterface* sink) override;
119
120 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
121
122 // API methods
123
124 void StartPlayout() override;
125 void StopPlayout() override;
126
127 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000128 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
129 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100130
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100131 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100132
133 // RtpPacketSinkInterface.
134 void OnRtpPacket(const RtpPacketReceived& packet) override;
135
136 // Muting, Volume and Level.
137 void SetChannelOutputVolumeScaling(float scaling) override;
138 int GetSpeechOutputLevelFullRange() const override;
139 // See description of "totalAudioEnergy" in the WebRTC stats spec:
140 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
141 double GetTotalOutputEnergy() const override;
142 double GetTotalOutputDuration() const override;
143
144 // Stats.
145 NetworkStatistics GetNetworkStatistics() const override;
146 AudioDecodingCallStats GetDecodingCallStatistics() const override;
147
148 // Audio+Video Sync.
149 uint32_t GetDelayEstimate() const override;
150 void SetMinimumPlayoutDelay(int delayMs) override;
151 uint32_t GetPlayoutTimestamp() const override;
152
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100153 // Audio quality.
154 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
155 int GetBaseMinimumPlayoutDelayMs() const override;
156
Niels Möller349ade32018-11-16 09:50:42 +0100157 // Produces the transport-related timestamps; current_delay_ms is left unset.
158 absl::optional<Syncable::Info> GetSyncInfo() const override;
159
Niels Möller349ade32018-11-16 09:50:42 +0100160 void RegisterReceiverCongestionControlObjects(
161 PacketRouter* packet_router) override;
162 void ResetReceiverCongestionControlObjects() override;
163
164 CallReceiveStatistics GetRTCPStatistics() const override;
165 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
166
167 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
168 int sample_rate_hz,
169 AudioFrame* audio_frame) override;
170
171 int PreferredSampleRate() const override;
172
173 // Associate to a send channel.
174 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100175 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100176
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700177 // TODO(sukhanov): Return const pointer. It requires making media transport
178 // getters like GetLatestTargetTransferRate to be also const.
179 MediaTransportInterface* media_transport() const {
180 return media_transport_config_.media_transport;
181 }
182
Niels Möller349ade32018-11-16 09:50:42 +0100183 private:
Niels Möllered44f542019-07-30 15:15:59 +0200184 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100185 size_t packet_length,
186 const RTPHeader& header);
187 int ResendPackets(const uint16_t* sequence_numbers, int length);
188 void UpdatePlayoutTimestamp(bool rtcp);
189
190 int GetRtpTimestampRateHz() const;
191 int64_t GetRTT() const;
192
193 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000194 void OnData(uint64_t channel_id,
195 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100196
Niels Möllered44f542019-07-30 15:15:59 +0200197 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
198 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100199
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100200 bool Playing() const {
201 rtc::CritScope lock(&playing_lock_);
202 return playing_;
203 }
204
Niels Möller349ade32018-11-16 09:50:42 +0100205 // Thread checkers document and lock usage of some methods to specific threads
206 // we know about. The goal is to eventually split up voe::ChannelReceive into
207 // parts with single-threaded semantics, and thereby reduce the need for
208 // locks.
209 rtc::ThreadChecker worker_thread_checker_;
210 rtc::ThreadChecker module_process_thread_checker_;
211 // Methods accessed from audio and video threads are checked for sequential-
212 // only access. We don't necessarily own and control these threads, so thread
213 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
214 // audio thread to another, but access is still sequential.
215 rtc::RaceChecker audio_thread_race_checker_;
216 rtc::RaceChecker video_capture_thread_race_checker_;
217 rtc::CriticalSection _callbackCritSect;
218 rtc::CriticalSection volume_settings_critsect_;
219
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100220 rtc::CriticalSection playing_lock_;
221 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100222
223 RtcEventLog* const event_log_;
224
225 // Indexed by payload type.
226 std::map<uint8_t, int> payload_type_frequencies_;
227
228 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
229 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
230 const uint32_t remote_ssrc_;
231
Chen Xing054e3bb2019-08-02 10:29:26 +0000232 // Info for GetSyncInfo is updated on network or worker thread, and queried on
233 // the worker thread.
234 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100235 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000236 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100237 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000238 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100239
Niels Möllered44f542019-07-30 15:15:59 +0200240 // The AcmReceiver is thread safe, using its own lock.
241 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100242 AudioSinkInterface* audio_sink_ = nullptr;
243 AudioLevel _outputAudioLevel;
244
245 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
246
247 // Timestamp of the audio pulled from NetEq.
248 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
249
250 rtc::CriticalSection video_sync_lock_;
251 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
252 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
253
254 rtc::CriticalSection ts_stats_lock_;
255
256 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
257 // The rtp timestamp of the first played out audio frame.
258 int64_t capture_start_rtp_time_stamp_;
259 // The capture ntp time (in local timebase) of the first played out audio
260 // frame.
261 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
262
263 // uses
264 ProcessThread* _moduleProcessThreadPtr;
265 AudioDeviceModule* _audioDeviceModulePtr;
266 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
267
268 // An associated send channel.
269 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100270 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100271 RTC_GUARDED_BY(assoc_send_channel_lock_);
272
273 PacketRouter* packet_router_ = nullptr;
274
275 rtc::ThreadChecker construction_thread_;
276
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700277 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100278
279 // E2EE Audio Frame Decryption
280 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
281 webrtc::CryptoOptions crypto_options_;
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700282
283 const bool use_standard_bytes_stats_;
Niels Möller349ade32018-11-16 09:50:42 +0100284};
Niels Möller530ead42018-10-04 14:28:39 +0200285
Niels Möllered44f542019-07-30 15:15:59 +0200286void ChannelReceive::OnReceivedPayloadData(
287 rtc::ArrayView<const uint8_t> payload,
288 const RTPHeader& rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200289 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700290 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200291
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100292 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200293 // Avoid inserting into NetEQ when we are not playing. Count the
294 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200295 return;
Niels Möller530ead42018-10-04 14:28:39 +0200296 }
297
298 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200299 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200300 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
301 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200302 return;
Niels Möller530ead42018-10-04 14:28:39 +0200303 }
304
305 int64_t round_trip_time = 0;
306 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
307
Niels Möllered44f542019-07-30 15:15:59 +0200308 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200309 if (!nack_list.empty()) {
310 // Can't use nack_list.data() since it's not supported by all
311 // compilers.
312 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
313 }
Niels Möller530ead42018-10-04 14:28:39 +0200314}
315
Niels Möller7d76a312018-10-26 12:57:07 +0200316// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000317void ChannelReceive::OnData(uint64_t channel_id,
318 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700319 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200320
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100321 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200322 // Avoid inserting into NetEQ when we are not playing. Count the
323 // packet as discarded.
324 return;
325 }
326
327 // Send encoded audio frame to Decoder / NetEq.
Niels Möllered44f542019-07-30 15:15:59 +0200328 if (acm_receiver_.InsertPacket(
329 CreateRTPHeaderForMediaTransportFrame(frame, channel_id),
330 frame.encoded_data()) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200331 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
332 "push data to the ACM";
333 }
334}
335
Niels Möller530ead42018-10-04 14:28:39 +0200336AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
337 int sample_rate_hz,
338 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100339 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200340 audio_frame->sample_rate_hz_ = sample_rate_hz;
341
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100342 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
343
Niels Möller530ead42018-10-04 14:28:39 +0200344 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
345 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200346 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
347 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200348 RTC_DLOG(LS_ERROR)
349 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
350 // In all likelihood, the audio in this frame is garbage. We return an
351 // error so that the audio mixer module doesn't add it to the mix. As
352 // a result, it won't be played out and the actions skipped here are
353 // irrelevant.
354 return AudioMixer::Source::AudioFrameInfo::kError;
355 }
356
357 if (muted) {
358 // TODO(henrik.lundin): We should be able to do better than this. But we
359 // will have to go through all the cases below where the audio samples may
360 // be used, and handle the muted case in some way.
361 AudioFrameOperations::Mute(audio_frame);
362 }
363
364 {
365 // Pass the audio buffers to an optional sink callback, before applying
366 // scaling/panning, as that applies to the mix operation.
367 // External recipients of the audio (e.g. via AudioTrack), will do their
368 // own mixing/dynamic processing.
369 rtc::CritScope cs(&_callbackCritSect);
370 if (audio_sink_) {
371 AudioSinkInterface::Data data(
372 audio_frame->data(), audio_frame->samples_per_channel_,
373 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
374 audio_frame->timestamp_);
375 audio_sink_->OnData(data);
376 }
377 }
378
379 float output_gain = 1.0f;
380 {
381 rtc::CritScope cs(&volume_settings_critsect_);
382 output_gain = _outputGain;
383 }
384
385 // Output volume scaling
386 if (output_gain < 0.99f || output_gain > 1.01f) {
387 // TODO(solenberg): Combine with mute state - this can cause clicks!
388 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
389 }
390
391 // Measure audio level (0-9)
392 // TODO(henrik.lundin) Use the |muted| information here too.
393 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
394 // https://crbug.com/webrtc/7517).
395 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
396
397 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
398 // The first frame with a valid rtp timestamp.
399 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
400 }
401
402 if (capture_start_rtp_time_stamp_ >= 0) {
403 // audio_frame.timestamp_ should be valid from now on.
404
405 // Compute elapsed time.
406 int64_t unwrap_timestamp =
407 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
408 audio_frame->elapsed_time_ms_ =
409 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
410 (GetRtpTimestampRateHz() / 1000);
411
412 {
413 rtc::CritScope lock(&ts_stats_lock_);
414 // Compute ntp time.
415 audio_frame->ntp_time_ms_ =
416 ntp_estimator_.Estimate(audio_frame->timestamp_);
417 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
418 if (audio_frame->ntp_time_ms_ > 0) {
419 // Compute |capture_start_ntp_time_ms_| so that
420 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
421 capture_start_ntp_time_ms_ =
422 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
423 }
424 }
425 }
426
427 {
428 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200429 acm_receiver_.TargetDelayMs());
430 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200431 rtc::CritScope lock(&video_sync_lock_);
432 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
433 jitter_buffer_delay + playout_delay_ms_);
434 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
435 jitter_buffer_delay);
436 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
437 playout_delay_ms_);
438 }
439
440 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
441 : AudioMixer::Source::AudioFrameInfo::kNormal;
442}
443
444int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100445 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200446 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200447 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
448 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200449}
450
451ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100452 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200453 ProcessThread* module_process_thread,
454 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700455 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200456 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200457 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200458 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200459 uint32_t remote_ssrc,
460 size_t jitter_buffer_max_packets,
461 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100462 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100463 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200464 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700465 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700466 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700467 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200468 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100469 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200470 remote_ssrc_(remote_ssrc),
Niels Möllered44f542019-07-30 15:15:59 +0200471 acm_receiver_(AcmConfig(decoder_factory,
472 codec_pair_id,
473 jitter_buffer_max_packets,
474 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200475 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100476 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200477 playout_timestamp_rtp_(0),
478 playout_delay_ms_(0),
479 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
480 capture_start_rtp_time_stamp_(-1),
481 capture_start_ntp_time_ms_(-1),
482 _moduleProcessThreadPtr(module_process_thread),
483 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200484 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700485 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700486 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700487 frame_decryptor_(frame_decryptor),
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700488 crypto_options_(crypto_options),
489 use_standard_bytes_stats_(
490 webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) {
Niels Möller349ade32018-11-16 09:50:42 +0100491 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200492 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100493
Niels Möller530ead42018-10-04 14:28:39 +0200494 RTC_DCHECK(module_process_thread);
495 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200496
497 acm_receiver_.ResetInitialDelay();
498 acm_receiver_.SetMinimumDelay(0);
499 acm_receiver_.SetMaximumDelay(0);
500 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200501
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200502 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200503
504 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
505 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100506 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200507 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100508 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200509 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200510 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200511 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200512 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200513
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100514 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200515 _rtpRtcpModule->SetSendingMediaStatus(false);
516 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200517
Niels Möller530ead42018-10-04 14:28:39 +0200518 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
519
Niels Möllerb6220d92019-08-29 13:47:09 +0200520 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200521 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200522
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700523 if (media_transport()) {
524 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200525 }
Niels Möller530ead42018-10-04 14:28:39 +0200526}
527
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100528ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200529 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200530
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700531 if (media_transport()) {
532 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200533 }
534
Niels Möller530ead42018-10-04 14:28:39 +0200535 StopPlayout();
536
Niels Möller530ead42018-10-04 14:28:39 +0200537 if (_moduleProcessThreadPtr)
538 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200539}
540
541void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200542 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200543 rtc::CritScope cs(&_callbackCritSect);
544 audio_sink_ = sink;
545}
546
Niels Möller80c67622018-11-12 13:22:47 +0100547void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200548 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100549 rtc::CritScope lock(&playing_lock_);
550 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200551}
552
Niels Möller80c67622018-11-12 13:22:47 +0100553void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200554 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100555 rtc::CritScope lock(&playing_lock_);
556 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200557 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200558}
559
Jonas Olssona4d87372019-07-05 19:08:33 +0200560absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
561 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200562 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200563 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200564}
565
Niels Möller530ead42018-10-04 14:28:39 +0200566void ChannelReceive::SetReceiveCodecs(
567 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200568 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200569 for (const auto& kv : codecs) {
570 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
571 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
572 }
Niels Möllered44f542019-07-30 15:15:59 +0200573 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200574}
575
Niels Möller349ade32018-11-16 09:50:42 +0100576// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200577void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
578 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200579
580 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000581 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200582 last_received_rtp_timestamp_ = packet.Timestamp();
583 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200584 }
585
586 // Store playout timestamp for the received RTP packet
587 UpdatePlayoutTimestamp(false);
588
589 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
590 if (it == payload_type_frequencies_.end())
591 return;
592 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
593 RtpPacketReceived packet_copy(packet);
594 packet_copy.set_payload_type_frequency(it->second);
595
596 rtp_receive_statistics_->OnRtpPacket(packet_copy);
597
598 RTPHeader header;
599 packet_copy.GetHeader(&header);
600
601 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
602}
603
Niels Möllered44f542019-07-30 15:15:59 +0200604void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200605 size_t packet_length,
606 const RTPHeader& header) {
607 const uint8_t* payload = packet + header.headerLength;
608 assert(packet_length >= header.headerLength);
609 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200610
Benjamin Wright84583f62018-10-04 14:22:34 -0700611 size_t payload_data_length = payload_length - header.paddingLength;
612
613 // E2EE Custom Audio Frame Decryption (This is optional).
614 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
615 rtc::Buffer decrypted_audio_payload;
616 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000617 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700618 cricket::MEDIA_TYPE_AUDIO, payload_length);
619 decrypted_audio_payload.SetSize(max_plaintext_size);
620
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000621 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
622 header.arrOfCSRCs + header.numCSRCs);
623 const FrameDecryptorInterface::Result decrypt_result =
624 frame_decryptor_->Decrypt(
625 cricket::MEDIA_TYPE_AUDIO, csrcs,
626 /*additional_data=*/nullptr,
627 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
628 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700629
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000630 if (decrypt_result.IsOk()) {
631 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
632 } else {
633 // Interpret failures as a silent frame.
634 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700635 }
636
Benjamin Wright84583f62018-10-04 14:22:34 -0700637 payload = decrypted_audio_payload.data();
638 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700639 } else if (crypto_options_.sframe.require_frame_encryption) {
640 RTC_DLOG(LS_ERROR)
641 << "FrameDecryptor required but not set, dropping packet";
642 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700643 }
644
Niels Möllered44f542019-07-30 15:15:59 +0200645 OnReceivedPayloadData(
646 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200647}
648
Niels Möller349ade32018-11-16 09:50:42 +0100649// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100650void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200651 // Store playout timestamp for the received RTCP packet
652 UpdatePlayoutTimestamp(true);
653
654 // Deliver RTCP packet to RTP/RTCP module for parsing
655 _rtpRtcpModule->IncomingRtcpPacket(data, length);
656
657 int64_t rtt = GetRTT();
658 if (rtt == 0) {
659 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100660 return;
Niels Möller530ead42018-10-04 14:28:39 +0200661 }
662
Niels Möller530ead42018-10-04 14:28:39 +0200663 uint32_t ntp_secs = 0;
664 uint32_t ntp_frac = 0;
665 uint32_t rtp_timestamp = 0;
666 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
667 &rtp_timestamp)) {
668 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100669 return;
Niels Möller530ead42018-10-04 14:28:39 +0200670 }
671
672 {
673 rtc::CritScope lock(&ts_stats_lock_);
674 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
675 }
Niels Möller530ead42018-10-04 14:28:39 +0200676}
677
678int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200679 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200680 return _outputAudioLevel.LevelFullRange();
681}
682
683double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200684 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200685 return _outputAudioLevel.TotalEnergy();
686}
687
688double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200689 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200690 return _outputAudioLevel.TotalDuration();
691}
692
693void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200694 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200695 rtc::CritScope cs(&volume_settings_critsect_);
696 _outputGain = scaling;
697}
698
Niels Möller530ead42018-10-04 14:28:39 +0200699void ChannelReceive::RegisterReceiverCongestionControlObjects(
700 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200701 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200702 RTC_DCHECK(packet_router);
703 RTC_DCHECK(!packet_router_);
704 constexpr bool remb_candidate = false;
705 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
706 packet_router_ = packet_router;
707}
708
709void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200710 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200711 RTC_DCHECK(packet_router_);
712 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
713 packet_router_ = nullptr;
714}
715
Niels Möller349ade32018-11-16 09:50:42 +0100716CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200717 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200718 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100719 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200720
721 // The jitter statistics is updated for each received RTP packet and is
722 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200723 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200724 StreamStatistician* statistician =
725 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
726 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200727 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200728 }
729
Niels Möllerd77cc242019-08-22 09:40:25 +0200730 stats.cumulativeLost = rtp_stats.packets_lost;
731 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200732
733 // --- RTT
734 stats.rttMs = GetRTT();
735
736 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200737 if (statistician) {
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700738 if (use_standard_bytes_stats_) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200739 stats.bytesReceived = rtp_stats.packet_counter.payload_bytes;
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700740 } else {
Niels Möllerd77cc242019-08-22 09:40:25 +0200741 stats.bytesReceived = rtp_stats.packet_counter.TotalBytes();
Bjorn A Mellemda4f0932019-07-30 08:34:03 -0700742 }
Niels Möllerd77cc242019-08-22 09:40:25 +0200743 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200744 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200745 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200746 } else {
747 stats.bytesReceived = 0;
748 stats.packetsReceived = 0;
749 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200750 }
751
Niels Möller530ead42018-10-04 14:28:39 +0200752 // --- Timestamps
753 {
754 rtc::CritScope lock(&ts_stats_lock_);
755 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
756 }
Niels Möller80c67622018-11-12 13:22:47 +0100757 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200758}
759
Niels Möller349ade32018-11-16 09:50:42 +0100760void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200761 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200762 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100763 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200764 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
765 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100766 } else {
767 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200768 kDefaultMaxReorderingThreshold);
769 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100770 }
Niels Möller530ead42018-10-04 14:28:39 +0200771}
772
773// Called when we are missing one or more packets.
774int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
775 int length) {
776 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
777}
778
Niels Möllerdced9f62018-11-19 10:27:07 +0100779void ChannelReceive::SetAssociatedSendChannel(
780 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200781 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200782 rtc::CritScope lock(&assoc_send_channel_lock_);
783 associated_send_channel_ = channel;
784}
785
Niels Möller80c67622018-11-12 13:22:47 +0100786NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200787 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100788 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200789 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100790 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200791}
792
Niels Möller80c67622018-11-12 13:22:47 +0100793AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200794 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100795 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200796 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100797 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200798}
799
800uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200801 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
802 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200803 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200804 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200805}
806
Niels Möller349ade32018-11-16 09:50:42 +0100807void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200808 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100809 // Limit to range accepted by both VoE and ACM, so we're at least getting as
810 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100811 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
812 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200813 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200814 RTC_DLOG(LS_ERROR)
815 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200816 }
Niels Möller530ead42018-10-04 14:28:39 +0200817}
818
Niels Möller349ade32018-11-16 09:50:42 +0100819uint32_t ChannelReceive::GetPlayoutTimestamp() const {
820 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200821 {
822 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100823 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200824 }
Niels Möller530ead42018-10-04 14:28:39 +0200825}
826
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100827bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200828 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100829}
830
831int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200832 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100833}
834
Niels Möller530ead42018-10-04 14:28:39 +0200835absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200836 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200837 Syncable::Info info;
838 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
839 &info.capture_time_ntp_frac, nullptr, nullptr,
840 &info.capture_time_source_clock) != 0) {
841 return absl::nullopt;
842 }
843 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000844 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200845 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
846 return absl::nullopt;
847 }
848 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
849 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
850 }
851 return info;
852}
853
854void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
Niels Möllered44f542019-07-30 15:15:59 +0200855 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200856
857 if (!jitter_buffer_playout_timestamp_) {
858 // This can happen if this channel has not received any RTP packets. In
859 // this case, NetEq is not capable of computing a playout timestamp.
860 return;
861 }
862
863 uint16_t delay_ms = 0;
864 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
865 RTC_DLOG(LS_WARNING)
866 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
867 << " playout delay from the ADM";
868 return;
869 }
870
871 RTC_DCHECK(jitter_buffer_playout_timestamp_);
872 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
873
874 // Remove the playout delay.
875 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
876
877 {
878 rtc::CritScope lock(&video_sync_lock_);
879 if (!rtcp) {
880 playout_timestamp_rtp_ = playout_timestamp;
881 }
882 playout_delay_ms_ = delay_ms;
883 }
884}
885
886int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200887 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200888 // Default to the playout frequency if we've not gotten any packets yet.
889 // TODO(ossu): Zero clockrate can only happen if we've added an external
890 // decoder for a format we don't support internally. Remove once that way of
891 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100892 return (decoder && decoder->second.clockrate_hz != 0)
893 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200894 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200895}
896
897int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700898 if (media_transport()) {
899 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800900 if (target_rate.has_value()) {
901 return target_rate->network_estimate.round_trip_time.ms();
902 }
903
904 return 0;
905 }
Niels Möller530ead42018-10-04 14:28:39 +0200906 std::vector<RTCPReportBlock> report_blocks;
907 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
908
909 // TODO(nisse): Could we check the return value from the ->RTT() call below,
910 // instead of checking if we have any report blocks?
911 if (report_blocks.empty()) {
912 rtc::CritScope lock(&assoc_send_channel_lock_);
913 // Tries to get RTT from an associated channel.
914 if (!associated_send_channel_) {
915 return 0;
916 }
917 return associated_send_channel_->GetRTT();
918 }
919
920 int64_t rtt = 0;
921 int64_t avg_rtt = 0;
922 int64_t max_rtt = 0;
923 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100924 // TODO(nisse): This method computes RTT based on sender reports, even though
925 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200926 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
927 0) {
928 return 0;
929 }
930 return rtt;
931}
932
Niels Möller349ade32018-11-16 09:50:42 +0100933} // namespace
934
935std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100936 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100937 ProcessThread* module_process_thread,
938 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700939 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100940 Transport* rtcp_send_transport,
941 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200942 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100943 uint32_t remote_ssrc,
944 size_t jitter_buffer_max_packets,
945 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100946 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100947 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100948 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
949 absl::optional<AudioCodecPairId> codec_pair_id,
950 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
951 const webrtc::CryptoOptions& crypto_options) {
952 return absl::make_unique<ChannelReceive>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700953 clock, module_process_thread, audio_device_module, media_transport_config,
Erik Språng70efdde2019-08-21 13:36:20 +0200954 rtcp_send_transport, rtc_event_log, local_ssrc, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100955 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100956 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
957 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100958}
959
Niels Möller530ead42018-10-04 14:28:39 +0200960} // namespace voe
961} // namespace webrtc