blob: 7567e3b2e33b945fc4bbe5d98e0b036efee62d35 [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öller349ade32018-11-16 09:50:42 +010021#include "audio/audio_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020022#include "audio/channel_send.h"
23#include "audio/utility/audio_frame_operations.h"
24#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
25#include "logging/rtc_event_log/rtc_event_log.h"
26#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
Niels Möller349ade32018-11-16 09:50:42 +010027#include "modules/audio_coding/include/audio_coding_module.h"
Niels Möller530ead42018-10-04 14:28:39 +020028#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öller349ade32018-11-16 09:50:42 +010074class ChannelReceive : public ChannelReceiveInterface,
75 public MediaTransportAudioSinkInterface {
76 public:
77 // Used for receive streams.
Sebastian Jansson977b3352019-03-04 17:43:34 +010078 ChannelReceive(Clock* clock,
79 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +010080 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -070081 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +010082 Transport* rtcp_send_transport,
83 RtcEventLog* rtc_event_log,
84 uint32_t remote_ssrc,
85 size_t jitter_buffer_max_packets,
86 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010087 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +010088 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +010089 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
90 absl::optional<AudioCodecPairId> codec_pair_id,
91 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
92 const webrtc::CryptoOptions& crypto_options);
93 ~ChannelReceive() override;
94
95 void SetSink(AudioSinkInterface* sink) override;
96
97 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
98
99 // API methods
100
101 void StartPlayout() override;
102 void StopPlayout() override;
103
104 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000105 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
106 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100107
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100108 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100109
110 // RtpPacketSinkInterface.
111 void OnRtpPacket(const RtpPacketReceived& packet) override;
112
113 // Muting, Volume and Level.
114 void SetChannelOutputVolumeScaling(float scaling) override;
115 int GetSpeechOutputLevelFullRange() const override;
116 // See description of "totalAudioEnergy" in the WebRTC stats spec:
117 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
118 double GetTotalOutputEnergy() const override;
119 double GetTotalOutputDuration() const override;
120
121 // Stats.
122 NetworkStatistics GetNetworkStatistics() const override;
123 AudioDecodingCallStats GetDecodingCallStatistics() const override;
124
125 // Audio+Video Sync.
126 uint32_t GetDelayEstimate() const override;
127 void SetMinimumPlayoutDelay(int delayMs) override;
128 uint32_t GetPlayoutTimestamp() const override;
129
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100130 // Audio quality.
131 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
132 int GetBaseMinimumPlayoutDelayMs() const override;
133
Niels Möller349ade32018-11-16 09:50:42 +0100134 // Produces the transport-related timestamps; current_delay_ms is left unset.
135 absl::optional<Syncable::Info> GetSyncInfo() const override;
136
137 // RTP+RTCP
138 void SetLocalSSRC(unsigned int ssrc) override;
139
140 void RegisterReceiverCongestionControlObjects(
141 PacketRouter* packet_router) override;
142 void ResetReceiverCongestionControlObjects() override;
143
144 CallReceiveStatistics GetRTCPStatistics() const override;
145 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
146
147 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
148 int sample_rate_hz,
149 AudioFrame* audio_frame) override;
150
151 int PreferredSampleRate() const override;
152
153 // Associate to a send channel.
154 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100155 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100156
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700157 // TODO(sukhanov): Return const pointer. It requires making media transport
158 // getters like GetLatestTargetTransferRate to be also const.
159 MediaTransportInterface* media_transport() const {
160 return media_transport_config_.media_transport;
161 }
162
Niels Möller349ade32018-11-16 09:50:42 +0100163 private:
Niels Möller349ade32018-11-16 09:50:42 +0100164 bool ReceivePacket(const uint8_t* packet,
165 size_t packet_length,
166 const RTPHeader& header);
167 int ResendPackets(const uint16_t* sequence_numbers, int length);
168 void UpdatePlayoutTimestamp(bool rtcp);
169
170 int GetRtpTimestampRateHz() const;
171 int64_t GetRTT() const;
172
173 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000174 void OnData(uint64_t channel_id,
175 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100176
177 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
178 size_t payloadSize,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100179 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100180
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100181 bool Playing() const {
182 rtc::CritScope lock(&playing_lock_);
183 return playing_;
184 }
185
Niels Möller349ade32018-11-16 09:50:42 +0100186 // Thread checkers document and lock usage of some methods to specific threads
187 // we know about. The goal is to eventually split up voe::ChannelReceive into
188 // parts with single-threaded semantics, and thereby reduce the need for
189 // locks.
190 rtc::ThreadChecker worker_thread_checker_;
191 rtc::ThreadChecker module_process_thread_checker_;
192 // Methods accessed from audio and video threads are checked for sequential-
193 // only access. We don't necessarily own and control these threads, so thread
194 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
195 // audio thread to another, but access is still sequential.
196 rtc::RaceChecker audio_thread_race_checker_;
197 rtc::RaceChecker video_capture_thread_race_checker_;
198 rtc::CriticalSection _callbackCritSect;
199 rtc::CriticalSection volume_settings_critsect_;
200
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100201 rtc::CriticalSection playing_lock_;
202 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100203
204 RtcEventLog* const event_log_;
205
206 // Indexed by payload type.
207 std::map<uint8_t, int> payload_type_frequencies_;
208
209 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
210 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
211 const uint32_t remote_ssrc_;
212
Chen Xing8fa71512019-07-02 15:11:38 +0200213 // Info for GetSyncInfo is updated on network or worker thread, and queried on
214 // the worker thread.
215 rtc::CriticalSection sync_info_lock_;
Niels Möller349ade32018-11-16 09:50:42 +0100216 absl::optional<uint32_t> last_received_rtp_timestamp_
Chen Xing8fa71512019-07-02 15:11:38 +0200217 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100218 absl::optional<int64_t> last_received_rtp_system_time_ms_
Chen Xing8fa71512019-07-02 15:11:38 +0200219 RTC_GUARDED_BY(&sync_info_lock_);
Niels Möller349ade32018-11-16 09:50:42 +0100220
221 std::unique_ptr<AudioCodingModule> audio_coding_;
222 AudioSinkInterface* audio_sink_ = nullptr;
223 AudioLevel _outputAudioLevel;
224
225 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
226
227 // Timestamp of the audio pulled from NetEq.
228 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
229
230 rtc::CriticalSection video_sync_lock_;
231 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
232 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
233
234 rtc::CriticalSection ts_stats_lock_;
235
236 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
237 // The rtp timestamp of the first played out audio frame.
238 int64_t capture_start_rtp_time_stamp_;
239 // The capture ntp time (in local timebase) of the first played out audio
240 // frame.
241 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
242
243 // uses
244 ProcessThread* _moduleProcessThreadPtr;
245 AudioDeviceModule* _audioDeviceModulePtr;
246 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
247
248 // An associated send channel.
249 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100250 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100251 RTC_GUARDED_BY(assoc_send_channel_lock_);
252
253 PacketRouter* packet_router_ = nullptr;
254
255 rtc::ThreadChecker construction_thread_;
256
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700257 MediaTransportConfig media_transport_config_;
Niels Möller349ade32018-11-16 09:50:42 +0100258
259 // E2EE Audio Frame Decryption
260 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
261 webrtc::CryptoOptions crypto_options_;
262};
Niels Möller530ead42018-10-04 14:28:39 +0200263
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100264int32_t ChannelReceive::OnReceivedPayloadData(const uint8_t* payloadData,
265 size_t payloadSize,
266 const RTPHeader& rtp_header) {
Niels Möller7d76a312018-10-26 12:57:07 +0200267 // We should not be receiving any RTP packets if media_transport is set.
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700268 RTC_CHECK(!media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200269
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100270 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200271 // Avoid inserting into NetEQ when we are not playing. Count the
272 // packet as discarded.
273 return 0;
274 }
275
276 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100277 if (audio_coding_->IncomingPacket(payloadData, payloadSize, rtp_header) !=
Niels Möller530ead42018-10-04 14:28:39 +0200278 0) {
279 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
280 "push data to the ACM";
281 return -1;
282 }
283
284 int64_t round_trip_time = 0;
285 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
286
287 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
288 if (!nack_list.empty()) {
289 // Can't use nack_list.data() since it's not supported by all
290 // compilers.
291 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
292 }
293 return 0;
294}
295
Niels Möller7d76a312018-10-26 12:57:07 +0200296// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000297void ChannelReceive::OnData(uint64_t channel_id,
298 MediaTransportEncodedAudioFrame frame) {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700299 RTC_CHECK(media_transport());
Niels Möller7d76a312018-10-26 12:57:07 +0200300
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100301 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200302 // Avoid inserting into NetEQ when we are not playing. Count the
303 // packet as discarded.
304 return;
305 }
306
307 // Send encoded audio frame to Decoder / NetEq.
308 if (audio_coding_->IncomingPacket(
309 frame.encoded_data().data(), frame.encoded_data().size(),
Sergey Silkine049eba2019-02-18 09:52:26 +0000310 CreateRTPHeaderForMediaTransportFrame(frame, channel_id)) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200311 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
312 "push data to the ACM";
313 }
314}
315
Niels Möller530ead42018-10-04 14:28:39 +0200316AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
317 int sample_rate_hz,
318 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100319 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200320 audio_frame->sample_rate_hz_ = sample_rate_hz;
321
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100322 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
323
Niels Möller530ead42018-10-04 14:28:39 +0200324 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
325 bool muted;
326 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
327 &muted) == -1) {
328 RTC_DLOG(LS_ERROR)
329 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
330 // In all likelihood, the audio in this frame is garbage. We return an
331 // error so that the audio mixer module doesn't add it to the mix. As
332 // a result, it won't be played out and the actions skipped here are
333 // irrelevant.
334 return AudioMixer::Source::AudioFrameInfo::kError;
335 }
336
337 if (muted) {
338 // TODO(henrik.lundin): We should be able to do better than this. But we
339 // will have to go through all the cases below where the audio samples may
340 // be used, and handle the muted case in some way.
341 AudioFrameOperations::Mute(audio_frame);
342 }
343
344 {
345 // Pass the audio buffers to an optional sink callback, before applying
346 // scaling/panning, as that applies to the mix operation.
347 // External recipients of the audio (e.g. via AudioTrack), will do their
348 // own mixing/dynamic processing.
349 rtc::CritScope cs(&_callbackCritSect);
350 if (audio_sink_) {
351 AudioSinkInterface::Data data(
352 audio_frame->data(), audio_frame->samples_per_channel_,
353 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
354 audio_frame->timestamp_);
355 audio_sink_->OnData(data);
356 }
357 }
358
359 float output_gain = 1.0f;
360 {
361 rtc::CritScope cs(&volume_settings_critsect_);
362 output_gain = _outputGain;
363 }
364
365 // Output volume scaling
366 if (output_gain < 0.99f || output_gain > 1.01f) {
367 // TODO(solenberg): Combine with mute state - this can cause clicks!
368 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
369 }
370
371 // Measure audio level (0-9)
372 // TODO(henrik.lundin) Use the |muted| information here too.
373 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
374 // https://crbug.com/webrtc/7517).
375 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
376
377 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
378 // The first frame with a valid rtp timestamp.
379 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
380 }
381
382 if (capture_start_rtp_time_stamp_ >= 0) {
383 // audio_frame.timestamp_ should be valid from now on.
384
385 // Compute elapsed time.
386 int64_t unwrap_timestamp =
387 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
388 audio_frame->elapsed_time_ms_ =
389 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
390 (GetRtpTimestampRateHz() / 1000);
391
392 {
393 rtc::CritScope lock(&ts_stats_lock_);
394 // Compute ntp time.
395 audio_frame->ntp_time_ms_ =
396 ntp_estimator_.Estimate(audio_frame->timestamp_);
397 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
398 if (audio_frame->ntp_time_ms_ > 0) {
399 // Compute |capture_start_ntp_time_ms_| so that
400 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
401 capture_start_ntp_time_ms_ =
402 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
403 }
404 }
405 }
406
407 {
408 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
409 audio_coding_->TargetDelayMs());
410 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
411 rtc::CritScope lock(&video_sync_lock_);
412 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
413 jitter_buffer_delay + playout_delay_ms_);
414 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
415 jitter_buffer_delay);
416 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
417 playout_delay_ms_);
418 }
419
420 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
421 : AudioMixer::Source::AudioFrameInfo::kNormal;
422}
423
424int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100425 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200426 // Return the bigger of playout and receive frequency in the ACM.
427 return std::max(audio_coding_->ReceiveFrequency(),
428 audio_coding_->PlayoutFrequency());
429}
430
431ChannelReceive::ChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100432 Clock* clock,
Niels Möller530ead42018-10-04 14:28:39 +0200433 ProcessThread* module_process_thread,
434 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700435 const MediaTransportConfig& media_transport_config,
Niels Möllerae4237e2018-10-05 11:28:38 +0200436 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200437 RtcEventLog* rtc_event_log,
438 uint32_t remote_ssrc,
439 size_t jitter_buffer_max_packets,
440 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100441 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100442 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200443 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700444 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700445 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700446 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200447 : event_log_(rtc_event_log),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100448 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
Niels Möller530ead42018-10-04 14:28:39 +0200449 remote_ssrc_(remote_ssrc),
450 _outputAudioLevel(),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100451 ntp_estimator_(clock),
Niels Möller530ead42018-10-04 14:28:39 +0200452 playout_timestamp_rtp_(0),
453 playout_delay_ms_(0),
454 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
455 capture_start_rtp_time_stamp_(-1),
456 capture_start_ntp_time_ms_(-1),
457 _moduleProcessThreadPtr(module_process_thread),
458 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200459 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700460 associated_send_channel_(nullptr),
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700461 media_transport_config_(media_transport_config),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700462 frame_decryptor_(frame_decryptor),
463 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100464 // TODO(nisse): Use _moduleProcessThreadPtr instead?
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200465 module_process_thread_checker_.Detach();
Niels Möller349ade32018-11-16 09:50:42 +0100466
Niels Möller530ead42018-10-04 14:28:39 +0200467 RTC_DCHECK(module_process_thread);
468 RTC_DCHECK(audio_device_module);
469 AudioCodingModule::Config acm_config;
470 acm_config.decoder_factory = decoder_factory;
471 acm_config.neteq_config.codec_pair_id = codec_pair_id;
472 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
473 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100474 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200475 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100476 acm_config.neteq_config.enable_rtx_handling =
477 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200478 audio_coding_.reset(AudioCodingModule::Create(acm_config));
479
480 _outputAudioLevel.Clear();
481
482 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
483 RtpRtcp::Configuration configuration;
Sebastian Jansson977b3352019-03-04 17:43:34 +0100484 configuration.clock = clock;
Niels Möller530ead42018-10-04 14:28:39 +0200485 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100486 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200487 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200488 configuration.receive_statistics = rtp_receive_statistics_.get();
489
490 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200491
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100492 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200493 _rtpRtcpModule->SetSendingMediaStatus(false);
494 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200495
Niels Möller530ead42018-10-04 14:28:39 +0200496 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
497
Niels Möller530ead42018-10-04 14:28:39 +0200498 // Ensure that RTCP is enabled by default for the created channel.
499 // Note that, the module will keep generating RTCP until it is explicitly
500 // disabled by the user.
501 // After StopListen (when no sockets exists), RTCP packets will no longer
502 // be transmitted since the Transport object will then be invalid.
503 // RTCP is enabled by default.
504 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200505
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700506 if (media_transport()) {
507 media_transport()->SetReceiveAudioSink(this);
Niels Möller7d76a312018-10-26 12:57:07 +0200508 }
Niels Möller530ead42018-10-04 14:28:39 +0200509}
510
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100511ChannelReceive::~ChannelReceive() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200512 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller7d76a312018-10-26 12:57:07 +0200513
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700514 if (media_transport()) {
515 media_transport()->SetReceiveAudioSink(nullptr);
Niels Möller7d76a312018-10-26 12:57:07 +0200516 }
517
Niels Möller530ead42018-10-04 14:28:39 +0200518 StopPlayout();
519
Niels Möller530ead42018-10-04 14:28:39 +0200520 int error = audio_coding_->RegisterTransportCallback(NULL);
521 RTC_DCHECK_EQ(0, error);
522
Niels Möller530ead42018-10-04 14:28:39 +0200523 if (_moduleProcessThreadPtr)
524 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200525}
526
527void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200528 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200529 rtc::CritScope cs(&_callbackCritSect);
530 audio_sink_ = sink;
531}
532
Niels Möller80c67622018-11-12 13:22:47 +0100533void ChannelReceive::StartPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200534 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100535 rtc::CritScope lock(&playing_lock_);
536 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200537}
538
Niels Möller80c67622018-11-12 13:22:47 +0100539void ChannelReceive::StopPlayout() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200540 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100541 rtc::CritScope lock(&playing_lock_);
542 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200543 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200544}
545
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100546absl::optional<std::pair<int, SdpAudioFormat>>
547 ChannelReceive::GetReceiveCodec() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200548 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100549 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200550}
551
Niels Möller530ead42018-10-04 14:28:39 +0200552void ChannelReceive::SetReceiveCodecs(
553 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200554 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200555 for (const auto& kv : codecs) {
556 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
557 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
558 }
559 audio_coding_->SetReceiveCodecs(codecs);
560}
561
Niels Möller349ade32018-11-16 09:50:42 +0100562// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200563void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
564 int64_t now_ms = rtc::TimeMillis();
Niels Möller530ead42018-10-04 14:28:39 +0200565
566 {
Chen Xing8fa71512019-07-02 15:11:38 +0200567 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200568 last_received_rtp_timestamp_ = packet.Timestamp();
569 last_received_rtp_system_time_ms_ = now_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200570 }
571
572 // Store playout timestamp for the received RTP packet
573 UpdatePlayoutTimestamp(false);
574
575 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
576 if (it == payload_type_frequencies_.end())
577 return;
578 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
579 RtpPacketReceived packet_copy(packet);
580 packet_copy.set_payload_type_frequency(it->second);
581
582 rtp_receive_statistics_->OnRtpPacket(packet_copy);
583
584 RTPHeader header;
585 packet_copy.GetHeader(&header);
586
587 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
588}
589
590bool ChannelReceive::ReceivePacket(const uint8_t* packet,
591 size_t packet_length,
592 const RTPHeader& header) {
593 const uint8_t* payload = packet + header.headerLength;
594 assert(packet_length >= header.headerLength);
595 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200596
Benjamin Wright84583f62018-10-04 14:22:34 -0700597 size_t payload_data_length = payload_length - header.paddingLength;
598
599 // E2EE Custom Audio Frame Decryption (This is optional).
600 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
601 rtc::Buffer decrypted_audio_payload;
602 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000603 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700604 cricket::MEDIA_TYPE_AUDIO, payload_length);
605 decrypted_audio_payload.SetSize(max_plaintext_size);
606
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000607 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
608 header.arrOfCSRCs + header.numCSRCs);
609 const FrameDecryptorInterface::Result decrypt_result =
610 frame_decryptor_->Decrypt(
611 cricket::MEDIA_TYPE_AUDIO, csrcs,
612 /*additional_data=*/nullptr,
613 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
614 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700615
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000616 if (decrypt_result.IsOk()) {
617 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
618 } else {
619 // Interpret failures as a silent frame.
620 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700621 }
622
Benjamin Wright84583f62018-10-04 14:22:34 -0700623 payload = decrypted_audio_payload.data();
624 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700625 } else if (crypto_options_.sframe.require_frame_encryption) {
626 RTC_DLOG(LS_ERROR)
627 << "FrameDecryptor required but not set, dropping packet";
628 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700629 }
630
Niels Möller530ead42018-10-04 14:28:39 +0200631 if (payload_data_length == 0) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100632 return OnReceivedPayloadData(nullptr, 0, header);
Niels Möller530ead42018-10-04 14:28:39 +0200633 }
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100634 return OnReceivedPayloadData(payload, payload_data_length, header);
Niels Möller530ead42018-10-04 14:28:39 +0200635}
636
Niels Möller349ade32018-11-16 09:50:42 +0100637// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100638void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200639 // Store playout timestamp for the received RTCP packet
640 UpdatePlayoutTimestamp(true);
641
642 // Deliver RTCP packet to RTP/RTCP module for parsing
643 _rtpRtcpModule->IncomingRtcpPacket(data, length);
644
645 int64_t rtt = GetRTT();
646 if (rtt == 0) {
647 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100648 return;
Niels Möller530ead42018-10-04 14:28:39 +0200649 }
650
Niels Möller530ead42018-10-04 14:28:39 +0200651 uint32_t ntp_secs = 0;
652 uint32_t ntp_frac = 0;
653 uint32_t rtp_timestamp = 0;
654 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
655 &rtp_timestamp)) {
656 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100657 return;
Niels Möller530ead42018-10-04 14:28:39 +0200658 }
659
660 {
661 rtc::CritScope lock(&ts_stats_lock_);
662 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
663 }
Niels Möller530ead42018-10-04 14:28:39 +0200664}
665
666int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200667 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200668 return _outputAudioLevel.LevelFullRange();
669}
670
671double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200672 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200673 return _outputAudioLevel.TotalEnergy();
674}
675
676double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200677 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200678 return _outputAudioLevel.TotalDuration();
679}
680
681void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200682 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200683 rtc::CritScope cs(&volume_settings_critsect_);
684 _outputGain = scaling;
685}
686
Niels Möller349ade32018-11-16 09:50:42 +0100687void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200688 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200689 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200690}
691
Niels Möller530ead42018-10-04 14:28:39 +0200692void ChannelReceive::RegisterReceiverCongestionControlObjects(
693 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200694 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200695 RTC_DCHECK(packet_router);
696 RTC_DCHECK(!packet_router_);
697 constexpr bool remb_candidate = false;
698 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
699 packet_router_ = packet_router;
700}
701
702void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200703 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200704 RTC_DCHECK(packet_router_);
705 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
706 packet_router_ = nullptr;
707}
708
Niels Möller349ade32018-11-16 09:50:42 +0100709CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200710 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200711 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100712 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200713
714 // The jitter statistics is updated for each received RTP packet and is
715 // based on received packets.
716 RtcpStatistics statistics;
717 StreamStatistician* statistician =
718 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
719 if (statistician) {
720 statistician->GetStatistics(&statistics,
721 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
722 }
723
Niels Möller530ead42018-10-04 14:28:39 +0200724 stats.cumulativeLost = statistics.packets_lost;
725 stats.extendedMax = statistics.extended_highest_sequence_number;
726 stats.jitterSamples = statistics.jitter;
727
728 // --- RTT
729 stats.rttMs = GetRTT();
730
731 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200732 if (statistician) {
Henrik Boström01738c62019-04-15 17:32:00 +0200733 StreamDataCounters data_counters;
734 statistician->GetReceiveStreamDataCounters(&data_counters);
735 // TODO(http://crbug.com/webrtc/10525): Bytes received should only include
736 // payload bytes, not header and padding bytes.
737 stats.bytesReceived = data_counters.transmitted.payload_bytes +
738 data_counters.transmitted.header_bytes +
739 data_counters.transmitted.padding_bytes;
740 stats.packetsReceived = data_counters.transmitted.packets;
741 stats.last_packet_received_timestamp_ms =
742 data_counters.last_packet_received_timestamp_ms;
743 } else {
744 stats.bytesReceived = 0;
745 stats.packetsReceived = 0;
746 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200747 }
748
Niels Möller530ead42018-10-04 14:28:39 +0200749 // --- Timestamps
750 {
751 rtc::CritScope lock(&ts_stats_lock_);
752 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
753 }
Niels Möller80c67622018-11-12 13:22:47 +0100754 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200755}
756
Niels Möller349ade32018-11-16 09:50:42 +0100757void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200758 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200759 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100760 if (enable) {
Niels Möller87da1092019-05-24 14:04:28 +0200761 rtp_receive_statistics_->SetMaxReorderingThreshold(remote_ssrc_,
762 max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100763 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100764 } else {
765 rtp_receive_statistics_->SetMaxReorderingThreshold(
Niels Möller87da1092019-05-24 14:04:28 +0200766 remote_ssrc_, kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200767 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100768 }
Niels Möller530ead42018-10-04 14:28:39 +0200769}
770
771// Called when we are missing one or more packets.
772int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
773 int length) {
774 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
775}
776
Niels Möllerdced9f62018-11-19 10:27:07 +0100777void ChannelReceive::SetAssociatedSendChannel(
778 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200779 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200780 rtc::CritScope lock(&assoc_send_channel_lock_);
781 associated_send_channel_ = channel;
782}
783
Niels Möller80c67622018-11-12 13:22:47 +0100784NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200785 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100786 NetworkStatistics stats;
787 int error = audio_coding_->GetNetworkStatistics(&stats);
788 RTC_DCHECK_EQ(0, error);
789 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200790}
791
Niels Möller80c67622018-11-12 13:22:47 +0100792AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200793 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100794 AudioDecodingCallStats stats;
795 audio_coding_->GetDecodingCallStatistics(&stats);
796 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200797}
798
799uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200800 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
801 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200802 rtc::CritScope lock(&video_sync_lock_);
803 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
804}
805
Niels Möller349ade32018-11-16 09:50:42 +0100806void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200807 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100808 // Limit to range accepted by both VoE and ACM, so we're at least getting as
809 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100810 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
811 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100812 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200813 RTC_DLOG(LS_ERROR)
814 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200815 }
Niels Möller530ead42018-10-04 14:28:39 +0200816}
817
Niels Möller349ade32018-11-16 09:50:42 +0100818uint32_t ChannelReceive::GetPlayoutTimestamp() const {
819 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200820 {
821 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100822 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200823 }
Niels Möller530ead42018-10-04 14:28:39 +0200824}
825
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100826bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
827 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
828}
829
830int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
831 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
832}
833
Niels Möller530ead42018-10-04 14:28:39 +0200834absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200835 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200836 Syncable::Info info;
837 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
838 &info.capture_time_ntp_frac, nullptr, nullptr,
839 &info.capture_time_source_clock) != 0) {
840 return absl::nullopt;
841 }
842 {
Chen Xing8fa71512019-07-02 15:11:38 +0200843 rtc::CritScope cs(&sync_info_lock_);
Niels Möller530ead42018-10-04 14:28:39 +0200844 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
845 return absl::nullopt;
846 }
847 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
848 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
849 }
850 return info;
851}
852
853void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
854 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
855
856 if (!jitter_buffer_playout_timestamp_) {
857 // This can happen if this channel has not received any RTP packets. In
858 // this case, NetEq is not capable of computing a playout timestamp.
859 return;
860 }
861
862 uint16_t delay_ms = 0;
863 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
864 RTC_DLOG(LS_WARNING)
865 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
866 << " playout delay from the ADM";
867 return;
868 }
869
870 RTC_DCHECK(jitter_buffer_playout_timestamp_);
871 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
872
873 // Remove the playout delay.
874 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
875
876 {
877 rtc::CritScope lock(&video_sync_lock_);
878 if (!rtcp) {
879 playout_timestamp_rtp_ = playout_timestamp;
880 }
881 playout_delay_ms_ = delay_ms;
882 }
883}
884
885int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100886 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200887 // Default to the playout frequency if we've not gotten any packets yet.
888 // TODO(ossu): Zero clockrate can only happen if we've added an external
889 // decoder for a format we don't support internally. Remove once that way of
890 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100891 return (decoder && decoder->second.clockrate_hz != 0)
892 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200893 : audio_coding_->PlayoutFrequency();
894}
895
896int64_t ChannelReceive::GetRTT() const {
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700897 if (media_transport()) {
898 auto target_rate = media_transport()->GetLatestTargetTransferRate();
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800899 if (target_rate.has_value()) {
900 return target_rate->network_estimate.round_trip_time.ms();
901 }
902
903 return 0;
904 }
Niels Möller530ead42018-10-04 14:28:39 +0200905 RtcpMode method = _rtpRtcpModule->RTCP();
906 if (method == RtcpMode::kOff) {
907 return 0;
908 }
909 std::vector<RTCPReportBlock> report_blocks;
910 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
911
912 // TODO(nisse): Could we check the return value from the ->RTT() call below,
913 // instead of checking if we have any report blocks?
914 if (report_blocks.empty()) {
915 rtc::CritScope lock(&assoc_send_channel_lock_);
916 // Tries to get RTT from an associated channel.
917 if (!associated_send_channel_) {
918 return 0;
919 }
920 return associated_send_channel_->GetRTT();
921 }
922
923 int64_t rtt = 0;
924 int64_t avg_rtt = 0;
925 int64_t max_rtt = 0;
926 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100927 // TODO(nisse): This method computes RTT based on sender reports, even though
928 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200929 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
930 0) {
931 return 0;
932 }
933 return rtt;
934}
935
Niels Möller349ade32018-11-16 09:50:42 +0100936} // namespace
937
938std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100939 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100940 ProcessThread* module_process_thread,
941 AudioDeviceModule* audio_device_module,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700942 const MediaTransportConfig& media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100943 Transport* rtcp_send_transport,
944 RtcEventLog* rtc_event_log,
945 uint32_t remote_ssrc,
946 size_t jitter_buffer_max_packets,
947 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100948 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100949 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100950 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
951 absl::optional<AudioCodecPairId> codec_pair_id,
952 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
953 const webrtc::CryptoOptions& crypto_options) {
954 return absl::make_unique<ChannelReceive>(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -0700955 clock, module_process_thread, audio_device_module, media_transport_config,
Niels Möller349ade32018-11-16 09:50:42 +0100956 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100957 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100958 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
959 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100960}
961
Niels Möller530ead42018-10-04 14:28:39 +0200962} // namespace voe
963} // namespace webrtc