blob: fa1463a2e685bcddc48588b5fffc2d76f8bb1859 [file] [log] [blame]
Niels Möller530ead42018-10-04 14:28:39 +02001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "audio/channel_receive.h"
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
Niels Möllera8370302019-09-02 15:16:49 +020020#include "api/crypto/frame_decryptor_interface.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020021#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller349ade32018-11-16 09:50:42 +010022#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020023#include "audio/channel_send.h"
24#include "audio/utility/audio_frame_operations.h"
25#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möllered44f542019-07-30 15:15:59 +020026#include "modules/audio_coding/acm2/acm_receiver.h"
Niels Möller530ead42018-10-04 14:28:39 +020027#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
28#include "modules/audio_device/include/audio_device.h"
29#include "modules/pacing/packet_router.h"
30#include "modules/rtp_rtcp/include/receive_statistics.h"
Niels Möller349ade32018-11-16 09:50:42 +010031#include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
32#include "modules/rtp_rtcp/include/rtp_rtcp.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020034#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010035#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020036#include "modules/utility/include/process_thread.h"
37#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#include "rtc_base/format_macros.h"
40#include "rtc_base/location.h"
41#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010042#include "rtc_base/numerics/safe_minmax.h"
43#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020044#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020046#include "system_wrappers/include/metrics.h"
47
48namespace webrtc {
49namespace voe {
50
51namespace {
52
53constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020054
55// Video Sync.
56constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
57constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
58
Niels Möllerafb5dbb2019-02-15 15:21:47 +010059RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000060 const MediaTransportEncodedAudioFrame& frame,
61 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010062 webrtc::RTPHeader rtp_header;
63 rtp_header.payloadType = frame.payload_type();
64 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
65 rtp_header.timestamp = frame.starting_sample_index();
66 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020067
Sergey Silkine049eba2019-02-18 09:52:26 +000068 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020069
70 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010071 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020072}
73
Niels Möllered44f542019-07-30 15:15:59 +020074AudioCodingModule::Config AcmConfig(
75 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
76 absl::optional<AudioCodecPairId> codec_pair_id,
77 size_t jitter_buffer_max_packets,
78 bool jitter_buffer_fast_playout) {
79 AudioCodingModule::Config acm_config;
80 acm_config.decoder_factory = decoder_factory;
81 acm_config.neteq_config.codec_pair_id = codec_pair_id;
82 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
83 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
84 acm_config.neteq_config.enable_muted_state = true;
85
86 return acm_config;
87}
88
Niels Möller349ade32018-11-16 09:50:42 +010089class ChannelReceive : public ChannelReceiveInterface,
90 public MediaTransportAudioSinkInterface {
91 public:
92 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010093 ChannelReceive(Clock* clock,
94 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +010095 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -070096 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +010097 Transport* rtcp_send_transport,
98 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +020099 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100100 uint32_t remote_ssrc,
101 size_t jitter_buffer_max_packets,
102 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100103 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100104 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100105 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
106 absl::optional<AudioCodecPairId> codec_pair_id,
107 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
108 const webrtc::CryptoOptions& crypto_options);
109 ~ChannelReceive() override;
110
111 void SetSink(AudioSinkInterface* sink) override;
112
113 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
114
115 // API methods
116
117 void StartPlayout() override;
118 void StopPlayout() override;
119
120 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000121 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
122 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100123
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100124 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100125
126 // RtpPacketSinkInterface.
127 void OnRtpPacket(const RtpPacketReceived& packet) override;
128
129 // Muting, Volume and Level.
130 void SetChannelOutputVolumeScaling(float scaling) override;
131 int GetSpeechOutputLevelFullRange() const override;
132 // See description of "totalAudioEnergy" in the WebRTC stats spec:
133 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
134 double GetTotalOutputEnergy() const override;
135 double GetTotalOutputDuration() const override;
136
137 // Stats.
138 NetworkStatistics GetNetworkStatistics() const override;
139 AudioDecodingCallStats GetDecodingCallStatistics() const override;
140
141 // Audio+Video Sync.
142 uint32_t GetDelayEstimate() const override;
143 void SetMinimumPlayoutDelay(int delayMs) override;
144 uint32_t GetPlayoutTimestamp() const override;
145
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100146 // Audio quality.
147 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
148 int GetBaseMinimumPlayoutDelayMs() const override;
149
Niels Möller349ade32018-11-16 09:50:42 +0100150 // Produces the transport-related timestamps; current_delay_ms is left unset.
151 absl::optional<Syncable::Info> GetSyncInfo() const override;
152
Niels Möller349ade32018-11-16 09:50:42 +0100153 void RegisterReceiverCongestionControlObjects(
154 PacketRouter* packet_router) override;
155 void ResetReceiverCongestionControlObjects() override;
156
157 CallReceiveStatistics GetRTCPStatistics() const override;
158 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
159
160 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
161 int sample_rate_hz,
162 AudioFrame* audio_frame) override;
163
164 int PreferredSampleRate() const override;
165
166 // Associate to a send channel.
167 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100168 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100169
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700170 // TODO(sukhanov): Return const pointer. It requires making media transport
171 // getters like GetLatestTargetTransferRate to be also const.
172 MediaTransportInterface* media_transport() const {
173 return media_transport_config_.media_transport;
174 }
175
Niels Möller349ade32018-11-16 09:50:42 +0100176 private:
Niels Möllered44f542019-07-30 15:15:59 +0200177 void ReceivePacket(const uint8_t* packet,
Niels Möller349ade32018-11-16 09:50:42 +0100178 size_t packet_length,
179 const RTPHeader& header);
180 int ResendPackets(const uint16_t* sequence_numbers, int length);
181 void UpdatePlayoutTimestamp(bool rtcp);
182
183 int GetRtpTimestampRateHz() const;
184 int64_t GetRTT() const;
185
186 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000187 void OnData(uint64_t channel_id,
188 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100189
Niels Möllered44f542019-07-30 15:15:59 +0200190 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
191 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100192
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100193 bool Playing() const {
194 rtc::CritScope lock(&playing_lock_);
195 return playing_;
196 }
197
Niels Möller349ade32018-11-16 09:50:42 +0100198 // Thread checkers document and lock usage of some methods to specific threads
199 // we know about. The goal is to eventually split up voe::ChannelReceive into
200 // parts with single-threaded semantics, and thereby reduce the need for
201 // locks.
202 rtc::ThreadChecker worker_thread_checker_;
203 rtc::ThreadChecker module_process_thread_checker_;
204 // Methods accessed from audio and video threads are checked for sequential-
205 // only access. We don't necessarily own and control these threads, so thread
206 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
207 // audio thread to another, but access is still sequential.
208 rtc::RaceChecker audio_thread_race_checker_;
209 rtc::RaceChecker video_capture_thread_race_checker_;
210 rtc::CriticalSection _callbackCritSect;
211 rtc::CriticalSection volume_settings_critsect_;
212
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100213 rtc::CriticalSection playing_lock_;
214 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100215
216 RtcEventLog* const event_log_;
217
218 // Indexed by payload type.
219 std::map<uint8_t, int> payload_type_frequencies_;
220
221 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
222 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
223 const uint32_t remote_ssrc_;
224
Chen Xing054e3bb2019-08-02 10:29:26 +0000225 // Info for GetSyncInfo is updated on network or worker thread, and queried on
226 // the worker thread.
227 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100228 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing054e3bb2019-08-02 10:29:26 +0000229 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100230 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing054e3bb2019-08-02 10:29:26 +0000231 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100232
Niels Möllered44f542019-07-30 15:15:59 +0200233 // The AcmReceiver is thread safe, using its own lock.
234 acm2::AcmReceiver acm_receiver_;
Niels Möller349ade32018-11-16 09:50:42 +0100235 AudioSinkInterface* audio_sink_ = nullptr;
236 AudioLevel _outputAudioLevel;
237
238 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
239
240 // Timestamp of the audio pulled from NetEq.
241 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
242
243 rtc::CriticalSection video_sync_lock_;
244 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
245 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
246
247 rtc::CriticalSection ts_stats_lock_;
248
249 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
250 // The rtp timestamp of the first played out audio frame.
251 int64_t capture_start_rtp_time_stamp_;
252 // The capture ntp time (in local timebase) of the first played out audio
253 // frame.
254 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
255
256 // uses
257 ProcessThread* _moduleProcessThreadPtr;
258 AudioDeviceModule* _audioDeviceModulePtr;
259 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
260
261 // An associated send channel.
262 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100263 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100264 RTC_GUARDED_BY(assoc_send_channel_lock_);
265
266 PacketRouter* packet_router_ = nullptr;
267
268 rtc::ThreadChecker construction_thread_;
269
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700270 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100271
272 // E2EE Audio Frame Decryption
273 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
274 webrtc::CryptoOptions crypto_options_;
275};
Niels Möller530ead42018-10-04 14:28:39 +0200276
Niels Möllered44f542019-07-30 15:15:59 +0200277void ChannelReceive::OnReceivedPayloadData(
278 rtc::ArrayView<const uint8_t> payload,
279 const RTPHeader& rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200280 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700281 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200282
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100283 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200284 // Avoid inserting into NetEQ when we are not playing. Count the
285 // packet as discarded.
Niels Möllered44f542019-07-30 15:15:59 +0200286 return;
Niels Möller530ead42018-10-04 14:28:39 +0200287 }
288
289 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllered44f542019-07-30 15:15:59 +0200290 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200291 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
292 "push data to the ACM";
Niels Möllered44f542019-07-30 15:15:59 +0200293 return;
Niels Möller530ead42018-10-04 14:28:39 +0200294 }
295
296 int64_t round_trip_time = 0;
297 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
298
Niels Möllered44f542019-07-30 15:15:59 +0200299 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
Niels Möller530ead42018-10-04 14:28:39 +0200300 if (!nack_list.empty()) {
301 // Can't use nack_list.data() since it's not supported by all
302 // compilers.
303 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
304 }
Niels Möller530ead42018-10-04 14:28:39 +0200305}
306
Niels Möller7d76a312018-10-26 12:57:07 +0200307// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000308void ChannelReceive::OnData(uint64_t channel_id,
309 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700310 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200311
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100312 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200313 // Avoid inserting into NetEQ when we are not playing. Count the
314 // packet as discarded.
315 return;
316 }
317
318 // Send encoded audio frame to Decoder / NetEq.
Niels Möllered44f542019-07-30 15:15:59 +0200319 if (acm_receiver_.InsertPacket(
320 CreateRTPHeaderForMediaTransportFrame(frame, channel_id),
321 frame.encoded_data()) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200322 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
323 "push data to the ACM";
324 }
325}
326
Niels Möller530ead42018-10-04 14:28:39 +0200327AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
328 int sample_rate_hz,
329 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100330 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200331 audio_frame->sample_rate_hz_ = sample_rate_hz;
332
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200333 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100334
Niels Möller530ead42018-10-04 14:28:39 +0200335 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
336 bool muted;
Niels Möllered44f542019-07-30 15:15:59 +0200337 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
338 &muted) == -1) {
Niels Möller530ead42018-10-04 14:28:39 +0200339 RTC_DLOG(LS_ERROR)
340 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
341 // In all likelihood, the audio in this frame is garbage. We return an
342 // error so that the audio mixer module doesn't add it to the mix. As
343 // a result, it won't be played out and the actions skipped here are
344 // irrelevant.
345 return AudioMixer::Source::AudioFrameInfo::kError;
346 }
347
348 if (muted) {
349 // TODO(henrik.lundin): We should be able to do better than this. But we
350 // will have to go through all the cases below where the audio samples may
351 // be used, and handle the muted case in some way.
352 AudioFrameOperations::Mute(audio_frame);
353 }
354
355 {
356 // Pass the audio buffers to an optional sink callback, before applying
357 // scaling/panning, as that applies to the mix operation.
358 // External recipients of the audio (e.g. via AudioTrack), will do their
359 // own mixing/dynamic processing.
360 rtc::CritScope cs(&_callbackCritSect);
361 if (audio_sink_) {
362 AudioSinkInterface::Data data(
363 audio_frame->data(), audio_frame->samples_per_channel_,
364 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
365 audio_frame->timestamp_);
366 audio_sink_->OnData(data);
367 }
368 }
369
370 float output_gain = 1.0f;
371 {
372 rtc::CritScope cs(&volume_settings_critsect_);
373 output_gain = _outputGain;
374 }
375
376 // Output volume scaling
377 if (output_gain < 0.99f || output_gain > 1.01f) {
378 // TODO(solenberg): Combine with mute state - this can cause clicks!
379 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
380 }
381
382 // Measure audio level (0-9)
383 // TODO(henrik.lundin) Use the |muted| information here too.
384 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
385 // https://crbug.com/webrtc/7517).
386 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
387
388 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
389 // The first frame with a valid rtp timestamp.
390 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
391 }
392
393 if (capture_start_rtp_time_stamp_ >= 0) {
394 // audio_frame.timestamp_ should be valid from now on.
395
396 // Compute elapsed time.
397 int64_t unwrap_timestamp =
398 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
399 audio_frame->elapsed_time_ms_ =
400 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
401 (GetRtpTimestampRateHz() / 1000);
402
403 {
404 rtc::CritScope lock(&ts_stats_lock_);
405 // Compute ntp time.
406 audio_frame->ntp_time_ms_ =
407 ntp_estimator_.Estimate(audio_frame->timestamp_);
408 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
409 if (audio_frame->ntp_time_ms_ > 0) {
410 // Compute |capture_start_ntp_time_ms_| so that
411 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
412 capture_start_ntp_time_ms_ =
413 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
414 }
415 }
416 }
417
418 {
419 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
Niels Möllered44f542019-07-30 15:15:59 +0200420 acm_receiver_.TargetDelayMs());
421 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
Niels Möller530ead42018-10-04 14:28:39 +0200422 rtc::CritScope lock(&video_sync_lock_);
423 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
424 jitter_buffer_delay + playout_delay_ms_);
425 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
426 jitter_buffer_delay);
427 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
428 playout_delay_ms_);
429 }
430
431 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
432 : AudioMixer::Source::AudioFrameInfo::kNormal;
433}
434
435int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100436 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200437 // Return the bigger of playout and receive frequency in the ACM.
Niels Möllered44f542019-07-30 15:15:59 +0200438 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
439 acm_receiver_.last_output_sample_rate_hz());
Niels Möller530ead42018-10-04 14:28:39 +0200440}
441
442ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100443 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200444 ProcessThread* module_process_thread,
445 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700446 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200447 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200448 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200449 uint32_t local_ssrc,
Niels Möller530ead42018-10-04 14:28:39 +0200450 uint32_t remote_ssrc,
451 size_t jitter_buffer_max_packets,
452 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100453 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100454 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200455 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700456 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700457 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700458 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200459 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100460 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200461 remote_ssrc_(remote_ssrc),
Niels Möllered44f542019-07-30 15:15:59 +0200462 acm_receiver_(AcmConfig(decoder_factory,
463 codec_pair_id,
464 jitter_buffer_max_packets,
465 jitter_buffer_fast_playout)),
Niels Möller530ead42018-10-04 14:28:39 +0200466 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100467 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200468 playout_timestamp_rtp_(0),
469 playout_delay_ms_(0),
470 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
471 capture_start_rtp_time_stamp_(-1),
472 capture_start_ntp_time_ms_(-1),
473 _moduleProcessThreadPtr(module_process_thread),
474 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200475 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700476 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700477 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700478 frame_decryptor_(frame_decryptor),
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200479 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100480 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200481 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100482
Niels Möller530ead42018-10-04 14:28:39 +0200483 RTC_DCHECK(module_process_thread);
484 RTC_DCHECK(audio_device_module);
Niels Möllered44f542019-07-30 15:15:59 +0200485
486 acm_receiver_.ResetInitialDelay();
487 acm_receiver_.SetMinimumDelay(0);
488 acm_receiver_.SetMaximumDelay(0);
489 acm_receiver_.FlushBuffers();
Niels Möller530ead42018-10-04 14:28:39 +0200490
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200491 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200492
493 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
494 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100495 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200496 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100497 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200498 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200499 configuration.receive_statistics = rtp_receive_statistics_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200500 configuration.event_log = event_log_;
Erik Språng70efdde2019-08-21 13:36:20 +0200501 configuration.local_media_ssrc = local_ssrc;
Niels Möller530ead42018-10-04 14:28:39 +0200502
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100503 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200504 _rtpRtcpModule->SetSendingMediaStatus(false);
505 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200506
Niels Möller530ead42018-10-04 14:28:39 +0200507 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
508
Niels Möllerb6220d92019-08-29 13:47:09 +0200509 // Ensure that RTCP is enabled for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200510 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200511
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700512 if (media_transport()) {
513 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200514 }
Niels Möller530ead42018-10-04 14:28:39 +0200515}
516
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100517ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200518 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200519
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700520 if (media_transport()) {
521 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200522 }
523
Niels Möller530ead42018-10-04 14:28:39 +0200524 StopPlayout();
525
Niels Möller530ead42018-10-04 14:28:39 +0200526 if (_moduleProcessThreadPtr)
527 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200528}
529
530void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200531 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200532 rtc::CritScope cs(&_callbackCritSect);
533 audio_sink_ = sink;
534}
535
Niels Möller80c67622018-11-12 13:22:47 +0100536void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200537 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100538 rtc::CritScope lock(&playing_lock_);
539 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200540}
541
Niels Möller80c67622018-11-12 13:22:47 +0100542void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200543 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100544 rtc::CritScope lock(&playing_lock_);
545 playing_ = false;
Henrik Boströmd2c336f2019-07-03 17:11:10 +0200546 _outputAudioLevel.ResetLevelFullRange();
Niels Möller530ead42018-10-04 14:28:39 +0200547}
548
Jonas Olssona4d87372019-07-05 19:08:33 +0200549absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
550 const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200551 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möllered44f542019-07-30 15:15:59 +0200552 return acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200553}
554
Niels Möller530ead42018-10-04 14:28:39 +0200555void ChannelReceive::SetReceiveCodecs(
556 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200557 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200558 for (const auto& kv : codecs) {
559 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
560 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
561 }
Niels Möllered44f542019-07-30 15:15:59 +0200562 acm_receiver_.SetCodecs(codecs);
Niels Möller530ead42018-10-04 14:28:39 +0200563}
564
Niels Möller349ade32018-11-16 09:50:42 +0100565// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200566void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
567 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200568
569 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000570 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200571 last_received_rtp_timestamp_ = packet.Timestamp();
572 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200573 }
574
575 // Store playout timestamp for the received RTP packet
576 UpdatePlayoutTimestamp(false);
577
578 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
579 if (it == payload_type_frequencies_.end())
580 return;
581 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
582 RtpPacketReceived packet_copy(packet);
583 packet_copy.set_payload_type_frequency(it->second);
584
585 rtp_receive_statistics_->OnRtpPacket(packet_copy);
586
587 RTPHeader header;
588 packet_copy.GetHeader(&header);
589
590 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
591}
592
Niels Möllered44f542019-07-30 15:15:59 +0200593void ChannelReceive::ReceivePacket(const uint8_t* packet,
Niels Möller530ead42018-10-04 14:28:39 +0200594 size_t packet_length,
595 const RTPHeader& header) {
596 const uint8_t* payload = packet + header.headerLength;
597 assert(packet_length >= header.headerLength);
598 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200599
Benjamin Wright84583f62018-10-04 14:22:34 -0700600 size_t payload_data_length = payload_length - header.paddingLength;
601
602 // E2EE Custom Audio Frame Decryption (This is optional).
603 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
604 rtc::Buffer decrypted_audio_payload;
605 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000606 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700607 cricket::MEDIA_TYPE_AUDIO, payload_length);
608 decrypted_audio_payload.SetSize(max_plaintext_size);
609
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000610 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
611 header.arrOfCSRCs + header.numCSRCs);
612 const FrameDecryptorInterface::Result decrypt_result =
613 frame_decryptor_->Decrypt(
614 cricket::MEDIA_TYPE_AUDIO, csrcs,
615 /*additional_data=*/nullptr,
616 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
617 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700618
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000619 if (decrypt_result.IsOk()) {
620 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
621 } else {
622 // Interpret failures as a silent frame.
623 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700624 }
625
Benjamin Wright84583f62018-10-04 14:22:34 -0700626 payload = decrypted_audio_payload.data();
627 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700628 } else if (crypto_options_.sframe.require_frame_encryption) {
629 RTC_DLOG(LS_ERROR)
630 << "FrameDecryptor required but not set, dropping packet";
631 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700632 }
633
Niels Möllered44f542019-07-30 15:15:59 +0200634 OnReceivedPayloadData(
635 rtc::ArrayView<const uint8_t>(payload, payload_data_length), header);
Niels Möller530ead42018-10-04 14:28:39 +0200636}
637
Niels Möller349ade32018-11-16 09:50:42 +0100638// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100639void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200640 // Store playout timestamp for the received RTCP packet
641 UpdatePlayoutTimestamp(true);
642
643 // Deliver RTCP packet to RTP/RTCP module for parsing
644 _rtpRtcpModule->IncomingRtcpPacket(data, length);
645
646 int64_t rtt = GetRTT();
647 if (rtt == 0) {
648 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100649 return;
Niels Möller530ead42018-10-04 14:28:39 +0200650 }
651
Niels Möller530ead42018-10-04 14:28:39 +0200652 uint32_t ntp_secs = 0;
653 uint32_t ntp_frac = 0;
654 uint32_t rtp_timestamp = 0;
655 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
656 &rtp_timestamp)) {
657 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100658 return;
Niels Möller530ead42018-10-04 14:28:39 +0200659 }
660
661 {
662 rtc::CritScope lock(&ts_stats_lock_);
663 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
664 }
Niels Möller530ead42018-10-04 14:28:39 +0200665}
666
667int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200668 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200669 return _outputAudioLevel.LevelFullRange();
670}
671
672double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200673 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200674 return _outputAudioLevel.TotalEnergy();
675}
676
677double ChannelReceive::GetTotalOutputDuration() 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.TotalDuration();
680}
681
682void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200683 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200684 rtc::CritScope cs(&volume_settings_critsect_);
685 _outputGain = scaling;
686}
687
Niels Möller530ead42018-10-04 14:28:39 +0200688void ChannelReceive::RegisterReceiverCongestionControlObjects(
689 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200690 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200691 RTC_DCHECK(packet_router);
692 RTC_DCHECK(!packet_router_);
693 constexpr bool remb_candidate = false;
694 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
695 packet_router_ = packet_router;
696}
697
698void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200699 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200700 RTC_DCHECK(packet_router_);
701 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
702 packet_router_ = nullptr;
703}
704
Niels Möller349ade32018-11-16 09:50:42 +0100705CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200706 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200707 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100708 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200709
710 // The jitter statistics is updated for each received RTP packet and is
711 // based on received packets.
Niels Möllerd77cc242019-08-22 09:40:25 +0200712 RtpReceiveStats rtp_stats;
Niels Möller530ead42018-10-04 14:28:39 +0200713 StreamStatistician* statistician =
714 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
715 if (statistician) {
Niels Möllerd77cc242019-08-22 09:40:25 +0200716 rtp_stats = statistician->GetStats();
Niels Möller530ead42018-10-04 14:28:39 +0200717 }
718
Niels Möllerd77cc242019-08-22 09:40:25 +0200719 stats.cumulativeLost = rtp_stats.packets_lost;
720 stats.jitterSamples = rtp_stats.jitter;
Niels Möller530ead42018-10-04 14:28:39 +0200721
722 // --- RTT
723 stats.rttMs = GetRTT();
724
725 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200726 if (statistician) {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200727 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
728
729 stats.header_and_padding_bytes_rcvd =
730 rtp_stats.packet_counter.header_bytes +
731 rtp_stats.packet_counter.padding_bytes;
Niels Möllerd77cc242019-08-22 09:40:25 +0200732 stats.packetsReceived = rtp_stats.packet_counter.packets;
Henrik Boström01738c62019-04-15 17:32:00 +0200733 stats.last_packet_received_timestamp_ms =
Niels Möllerd77cc242019-08-22 09:40:25 +0200734 rtp_stats.last_packet_received_timestamp_ms;
Henrik Boström01738c62019-04-15 17:32:00 +0200735 } else {
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200736 stats.payload_bytes_rcvd = 0;
737 stats.header_and_padding_bytes_rcvd = 0;
Henrik Boström01738c62019-04-15 17:32:00 +0200738 stats.packetsReceived = 0;
739 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200740 }
741
Niels Möller530ead42018-10-04 14:28:39 +0200742 // --- Timestamps
743 {
744 rtc::CritScope lock(&ts_stats_lock_);
745 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
746 }
Niels Möller80c67622018-11-12 13:22:47 +0100747 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200748}
749
Niels Möller349ade32018-11-16 09:50:42 +0100750void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200751 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200752 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100753 if (enable) {
Niels Möllered44f542019-07-30 15:15:59 +0200754 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
755 acm_receiver_.EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100756 } else {
757 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möllered44f542019-07-30 15:15:59 +0200758 kDefaultMaxReorderingThreshold);
759 acm_receiver_.DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100760 }
Niels Möller530ead42018-10-04 14:28:39 +0200761}
762
763// Called when we are missing one or more packets.
764int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
765 int length) {
766 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
767}
768
Niels Möllerdced9f62018-11-19 10:27:07 +0100769void ChannelReceive::SetAssociatedSendChannel(
770 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200771 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200772 rtc::CritScope lock(&assoc_send_channel_lock_);
773 associated_send_channel_ = channel;
774}
775
Niels Möller80c67622018-11-12 13:22:47 +0100776NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200777 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100778 NetworkStatistics stats;
Niels Möllered44f542019-07-30 15:15:59 +0200779 acm_receiver_.GetNetworkStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100780 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200781}
782
Niels Möller80c67622018-11-12 13:22:47 +0100783AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200784 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100785 AudioDecodingCallStats stats;
Niels Möllered44f542019-07-30 15:15:59 +0200786 acm_receiver_.GetDecodingCallStatistics(&stats);
Niels Möller80c67622018-11-12 13:22:47 +0100787 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200788}
789
790uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200791 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
792 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200793 rtc::CritScope lock(&video_sync_lock_);
Niels Möllered44f542019-07-30 15:15:59 +0200794 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
Niels Möller530ead42018-10-04 14:28:39 +0200795}
796
Niels Möller349ade32018-11-16 09:50:42 +0100797void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200798 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100799 // Limit to range accepted by both VoE and ACM, so we're at least getting as
800 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100801 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
802 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möllered44f542019-07-30 15:15:59 +0200803 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200804 RTC_DLOG(LS_ERROR)
805 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200806 }
Niels Möller530ead42018-10-04 14:28:39 +0200807}
808
Niels Möller349ade32018-11-16 09:50:42 +0100809uint32_t ChannelReceive::GetPlayoutTimestamp() const {
810 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200811 {
812 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100813 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200814 }
Niels Möller530ead42018-10-04 14:28:39 +0200815}
816
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100817bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
Niels Möllered44f542019-07-30 15:15:59 +0200818 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100819}
820
821int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
Niels Möllered44f542019-07-30 15:15:59 +0200822 return acm_receiver_.GetBaseMinimumDelayMs();
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100823}
824
Niels Möller530ead42018-10-04 14:28:39 +0200825absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200826 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200827 Syncable::Info info;
828 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
829 &info.capture_time_ntp_frac, nullptr, nullptr,
830 &info.capture_time_source_clock) != 0) {
831 return absl::nullopt;
832 }
833 {
Chen Xing054e3bb2019-08-02 10:29:26 +0000834 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200835 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
836 return absl::nullopt;
837 }
838 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
839 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
840 }
841 return info;
842}
843
844void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
Niels Möllered44f542019-07-30 15:15:59 +0200845 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
Niels Möller530ead42018-10-04 14:28:39 +0200846
847 if (!jitter_buffer_playout_timestamp_) {
848 // This can happen if this channel has not received any RTP packets. In
849 // this case, NetEq is not capable of computing a playout timestamp.
850 return;
851 }
852
853 uint16_t delay_ms = 0;
854 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
855 RTC_DLOG(LS_WARNING)
856 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
857 << " playout delay from the ADM";
858 return;
859 }
860
861 RTC_DCHECK(jitter_buffer_playout_timestamp_);
862 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
863
864 // Remove the playout delay.
865 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
866
867 {
868 rtc::CritScope lock(&video_sync_lock_);
869 if (!rtcp) {
870 playout_timestamp_rtp_ = playout_timestamp;
871 }
872 playout_delay_ms_ = delay_ms;
873 }
874}
875
876int ChannelReceive::GetRtpTimestampRateHz() const {
Niels Möllered44f542019-07-30 15:15:59 +0200877 const auto decoder = acm_receiver_.LastDecoder();
Niels Möller530ead42018-10-04 14:28:39 +0200878 // Default to the playout frequency if we've not gotten any packets yet.
879 // TODO(ossu): Zero clockrate can only happen if we've added an external
880 // decoder for a format we don't support internally. Remove once that way of
881 // adding decoders is gone!
Karl Wiberg4b644112019-10-11 09:37:42 +0200882 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
883 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
884 // rate, which is not always the same thing.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100885 return (decoder && decoder->second.clockrate_hz != 0)
886 ? decoder->second.clockrate_hz
Niels Möllered44f542019-07-30 15:15:59 +0200887 : acm_receiver_.last_output_sample_rate_hz();
Niels Möller530ead42018-10-04 14:28:39 +0200888}
889
890int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700891 if (media_transport()) {
892 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800893 if (target_rate.has_value()) {
894 return target_rate->network_estimate.round_trip_time.ms();
895 }
896
897 return 0;
898 }
Niels Möller530ead42018-10-04 14:28:39 +0200899 std::vector<RTCPReportBlock> report_blocks;
900 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
901
902 // TODO(nisse): Could we check the return value from the ->RTT() call below,
903 // instead of checking if we have any report blocks?
904 if (report_blocks.empty()) {
905 rtc::CritScope lock(&assoc_send_channel_lock_);
906 // Tries to get RTT from an associated channel.
907 if (!associated_send_channel_) {
908 return 0;
909 }
910 return associated_send_channel_->GetRTT();
911 }
912
913 int64_t rtt = 0;
914 int64_t avg_rtt = 0;
915 int64_t max_rtt = 0;
916 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100917 // TODO(nisse): This method computes RTT based on sender reports, even though
918 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200919 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
920 0) {
921 return 0;
922 }
923 return rtt;
924}
925
Niels Möller349ade32018-11-16 09:50:42 +0100926} // namespace
927
928std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100929 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100930 ProcessThread* module_process_thread,
931 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700932 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100933 Transport* rtcp_send_transport,
934 RtcEventLog* rtc_event_log,
Erik Språng70efdde2019-08-21 13:36:20 +0200935 uint32_t local_ssrc,
Niels Möller349ade32018-11-16 09:50:42 +0100936 uint32_t remote_ssrc,
937 size_t jitter_buffer_max_packets,
938 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100939 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100940 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100941 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
942 absl::optional<AudioCodecPairId> codec_pair_id,
943 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
944 const webrtc::CryptoOptions& crypto_options) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200945 return std::make_unique<ChannelReceive>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700946 clock, module_process_thread, audio_device_module, media_transport_config,
Erik Språng70efdde2019-08-21 13:36:20 +0200947 rtcp_send_transport, rtc_event_log, local_ssrc, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100948 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100949 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
950 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100951}
952
Niels Möller530ead42018-10-04 14:28:39 +0200953} // namespace voe
954} // namespace webrtc