blob: 0e218edb10bc18389a9c8f55f81984e49f7af255 [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"
33#include "modules/rtp_rtcp/source/contributing_sources.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
Niels Möller530ead42018-10-04 14:28:39 +020035#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Danil Chapovalov2a977cf2018-12-04 18:03:52 +010036#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möller530ead42018-10-04 14:28:39 +020037#include "modules/utility/include/process_thread.h"
38#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/critical_section.h"
Niels Möller530ead42018-10-04 14:28:39 +020040#include "rtc_base/format_macros.h"
41#include "rtc_base/location.h"
42#include "rtc_base/logging.h"
Niels Möller349ade32018-11-16 09:50:42 +010043#include "rtc_base/numerics/safe_minmax.h"
44#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020045#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/time_utils.h"
Niels Möller530ead42018-10-04 14:28:39 +020047#include "system_wrappers/include/metrics.h"
48
49namespace webrtc {
50namespace voe {
51
52namespace {
53
54constexpr double kAudioSampleDurationSeconds = 0.01;
Niels Möller530ead42018-10-04 14:28:39 +020055
56// Video Sync.
57constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
58constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
59
Niels Möllerafb5dbb2019-02-15 15:21:47 +010060RTPHeader CreateRTPHeaderForMediaTransportFrame(
Sergey Silkine049eba2019-02-18 09:52:26 +000061 const MediaTransportEncodedAudioFrame& frame,
62 uint64_t channel_id) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +010063 webrtc::RTPHeader rtp_header;
64 rtp_header.payloadType = frame.payload_type();
65 rtp_header.payload_type_frequency = frame.sampling_rate_hz();
66 rtp_header.timestamp = frame.starting_sample_index();
67 rtp_header.sequenceNumber = frame.sequence_number();
Niels Möller7d76a312018-10-26 12:57:07 +020068
Sergey Silkine049eba2019-02-18 09:52:26 +000069 rtp_header.ssrc = static_cast<uint32_t>(channel_id);
Niels Möller7d76a312018-10-26 12:57:07 +020070
71 // The rest are initialized by the RTPHeader constructor.
Niels Möllerafb5dbb2019-02-15 15:21:47 +010072 return rtp_header;
Niels Möller7d76a312018-10-26 12:57:07 +020073}
74
Niels Möller349ade32018-11-16 09:50:42 +010075class ChannelReceive : public ChannelReceiveInterface,
76 public MediaTransportAudioSinkInterface {
77 public:
78 // Used for receive streams.
79 ChannelReceive(ProcessThread* module_process_thread,
80 AudioDeviceModule* audio_device_module,
81 MediaTransportInterface* media_transport,
82 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
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100105 absl::optional<std::pair<int, SdpAudioFormat>>
106 GetReceiveCodec() const override;
Niels Möller349ade32018-11-16 09:50:42 +0100107
108 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
109
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
157 std::vector<RtpSource> GetSources() const override;
158
159 private:
Niels Möller349ade32018-11-16 09:50:42 +0100160 bool ReceivePacket(const uint8_t* packet,
161 size_t packet_length,
162 const RTPHeader& header);
163 int ResendPackets(const uint16_t* sequence_numbers, int length);
164 void UpdatePlayoutTimestamp(bool rtcp);
165
166 int GetRtpTimestampRateHz() const;
167 int64_t GetRTT() const;
168
169 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000170 void OnData(uint64_t channel_id,
171 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100172
173 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
174 size_t payloadSize,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100175 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100176
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100177 bool Playing() const {
178 rtc::CritScope lock(&playing_lock_);
179 return playing_;
180 }
181
Niels Möller349ade32018-11-16 09:50:42 +0100182 // Thread checkers document and lock usage of some methods to specific threads
183 // we know about. The goal is to eventually split up voe::ChannelReceive into
184 // parts with single-threaded semantics, and thereby reduce the need for
185 // locks.
186 rtc::ThreadChecker worker_thread_checker_;
187 rtc::ThreadChecker module_process_thread_checker_;
188 // Methods accessed from audio and video threads are checked for sequential-
189 // only access. We don't necessarily own and control these threads, so thread
190 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
191 // audio thread to another, but access is still sequential.
192 rtc::RaceChecker audio_thread_race_checker_;
193 rtc::RaceChecker video_capture_thread_race_checker_;
194 rtc::CriticalSection _callbackCritSect;
195 rtc::CriticalSection volume_settings_critsect_;
196
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100197 rtc::CriticalSection playing_lock_;
198 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100199
200 RtcEventLog* const event_log_;
201
202 // Indexed by payload type.
203 std::map<uint8_t, int> payload_type_frequencies_;
204
205 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
206 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
207 const uint32_t remote_ssrc_;
208
209 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
210 // queried on the worker thread.
211 rtc::CriticalSection rtp_sources_lock_;
212 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
213 absl::optional<uint32_t> last_received_rtp_timestamp_
214 RTC_GUARDED_BY(&rtp_sources_lock_);
215 absl::optional<int64_t> last_received_rtp_system_time_ms_
216 RTC_GUARDED_BY(&rtp_sources_lock_);
217 absl::optional<uint8_t> last_received_rtp_audio_level_
218 RTC_GUARDED_BY(&rtp_sources_lock_);
219
220 std::unique_ptr<AudioCodingModule> audio_coding_;
221 AudioSinkInterface* audio_sink_ = nullptr;
222 AudioLevel _outputAudioLevel;
223
224 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
225
226 // Timestamp of the audio pulled from NetEq.
227 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
228
229 rtc::CriticalSection video_sync_lock_;
230 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
231 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
232
233 rtc::CriticalSection ts_stats_lock_;
234
235 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
236 // The rtp timestamp of the first played out audio frame.
237 int64_t capture_start_rtp_time_stamp_;
238 // The capture ntp time (in local timebase) of the first played out audio
239 // frame.
240 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
241
242 // uses
243 ProcessThread* _moduleProcessThreadPtr;
244 AudioDeviceModule* _audioDeviceModulePtr;
245 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
246
247 // An associated send channel.
248 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100249 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100250 RTC_GUARDED_BY(assoc_send_channel_lock_);
251
252 PacketRouter* packet_router_ = nullptr;
253
254 rtc::ThreadChecker construction_thread_;
255
256 MediaTransportInterface* const media_transport_;
257
258 // E2EE Audio Frame Decryption
259 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
260 webrtc::CryptoOptions crypto_options_;
261};
Niels Möller530ead42018-10-04 14:28:39 +0200262
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100263int32_t ChannelReceive::OnReceivedPayloadData(const uint8_t* payloadData,
264 size_t payloadSize,
265 const RTPHeader& rtp_header) {
Niels Möller7d76a312018-10-26 12:57:07 +0200266 // We should not be receiving any RTP packets if media_transport is set.
267 RTC_CHECK(!media_transport_);
268
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100269 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200270 // Avoid inserting into NetEQ when we are not playing. Count the
271 // packet as discarded.
272 return 0;
273 }
274
275 // Push the incoming payload (parsed and ready for decoding) into the ACM
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100276 if (audio_coding_->IncomingPacket(payloadData, payloadSize, rtp_header) !=
Niels Möller530ead42018-10-04 14:28:39 +0200277 0) {
278 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
279 "push data to the ACM";
280 return -1;
281 }
282
283 int64_t round_trip_time = 0;
284 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
285
286 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
287 if (!nack_list.empty()) {
288 // Can't use nack_list.data() since it's not supported by all
289 // compilers.
290 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
291 }
292 return 0;
293}
294
Niels Möller7d76a312018-10-26 12:57:07 +0200295// MediaTransportAudioSinkInterface override.
Sergey Silkine049eba2019-02-18 09:52:26 +0000296void ChannelReceive::OnData(uint64_t channel_id,
297 MediaTransportEncodedAudioFrame frame) {
Niels Möller7d76a312018-10-26 12:57:07 +0200298 RTC_CHECK(media_transport_);
299
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100300 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200301 // Avoid inserting into NetEQ when we are not playing. Count the
302 // packet as discarded.
303 return;
304 }
305
306 // Send encoded audio frame to Decoder / NetEq.
307 if (audio_coding_->IncomingPacket(
308 frame.encoded_data().data(), frame.encoded_data().size(),
Sergey Silkine049eba2019-02-18 09:52:26 +0000309 CreateRTPHeaderForMediaTransportFrame(frame, channel_id)) != 0) {
Niels Möller7d76a312018-10-26 12:57:07 +0200310 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
311 "push data to the ACM";
312 }
313}
314
Niels Möller530ead42018-10-04 14:28:39 +0200315AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
316 int sample_rate_hz,
317 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100318 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200319 audio_frame->sample_rate_hz_ = sample_rate_hz;
320
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100321 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
322
Niels Möller530ead42018-10-04 14:28:39 +0200323 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
324 bool muted;
325 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
326 &muted) == -1) {
327 RTC_DLOG(LS_ERROR)
328 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
329 // In all likelihood, the audio in this frame is garbage. We return an
330 // error so that the audio mixer module doesn't add it to the mix. As
331 // a result, it won't be played out and the actions skipped here are
332 // irrelevant.
333 return AudioMixer::Source::AudioFrameInfo::kError;
334 }
335
336 if (muted) {
337 // TODO(henrik.lundin): We should be able to do better than this. But we
338 // will have to go through all the cases below where the audio samples may
339 // be used, and handle the muted case in some way.
340 AudioFrameOperations::Mute(audio_frame);
341 }
342
343 {
344 // Pass the audio buffers to an optional sink callback, before applying
345 // scaling/panning, as that applies to the mix operation.
346 // External recipients of the audio (e.g. via AudioTrack), will do their
347 // own mixing/dynamic processing.
348 rtc::CritScope cs(&_callbackCritSect);
349 if (audio_sink_) {
350 AudioSinkInterface::Data data(
351 audio_frame->data(), audio_frame->samples_per_channel_,
352 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
353 audio_frame->timestamp_);
354 audio_sink_->OnData(data);
355 }
356 }
357
358 float output_gain = 1.0f;
359 {
360 rtc::CritScope cs(&volume_settings_critsect_);
361 output_gain = _outputGain;
362 }
363
364 // Output volume scaling
365 if (output_gain < 0.99f || output_gain > 1.01f) {
366 // TODO(solenberg): Combine with mute state - this can cause clicks!
367 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
368 }
369
370 // Measure audio level (0-9)
371 // TODO(henrik.lundin) Use the |muted| information here too.
372 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
373 // https://crbug.com/webrtc/7517).
374 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
375
376 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
377 // The first frame with a valid rtp timestamp.
378 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
379 }
380
381 if (capture_start_rtp_time_stamp_ >= 0) {
382 // audio_frame.timestamp_ should be valid from now on.
383
384 // Compute elapsed time.
385 int64_t unwrap_timestamp =
386 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
387 audio_frame->elapsed_time_ms_ =
388 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
389 (GetRtpTimestampRateHz() / 1000);
390
391 {
392 rtc::CritScope lock(&ts_stats_lock_);
393 // Compute ntp time.
394 audio_frame->ntp_time_ms_ =
395 ntp_estimator_.Estimate(audio_frame->timestamp_);
396 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
397 if (audio_frame->ntp_time_ms_ > 0) {
398 // Compute |capture_start_ntp_time_ms_| so that
399 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
400 capture_start_ntp_time_ms_ =
401 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
402 }
403 }
404 }
405
406 {
407 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
408 audio_coding_->TargetDelayMs());
409 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
410 rtc::CritScope lock(&video_sync_lock_);
411 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
412 jitter_buffer_delay + playout_delay_ms_);
413 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
414 jitter_buffer_delay);
415 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
416 playout_delay_ms_);
417 }
418
419 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
420 : AudioMixer::Source::AudioFrameInfo::kNormal;
421}
422
423int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100424 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200425 // Return the bigger of playout and receive frequency in the ACM.
426 return std::max(audio_coding_->ReceiveFrequency(),
427 audio_coding_->PlayoutFrequency());
428}
429
430ChannelReceive::ChannelReceive(
431 ProcessThread* module_process_thread,
432 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200433 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200434 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200435 RtcEventLog* rtc_event_log,
436 uint32_t remote_ssrc,
437 size_t jitter_buffer_max_packets,
438 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100439 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100440 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200441 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700442 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700443 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700444 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200445 : event_log_(rtc_event_log),
446 rtp_receive_statistics_(
447 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
448 remote_ssrc_(remote_ssrc),
449 _outputAudioLevel(),
450 ntp_estimator_(Clock::GetRealTimeClock()),
451 playout_timestamp_rtp_(0),
452 playout_delay_ms_(0),
453 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
454 capture_start_rtp_time_stamp_(-1),
455 capture_start_ntp_time_ms_(-1),
456 _moduleProcessThreadPtr(module_process_thread),
457 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200458 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700459 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200460 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700461 frame_decryptor_(frame_decryptor),
462 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100463 // TODO(nisse): Use _moduleProcessThreadPtr instead?
464 module_process_thread_checker_.DetachFromThread();
465
Niels Möller530ead42018-10-04 14:28:39 +0200466 RTC_DCHECK(module_process_thread);
467 RTC_DCHECK(audio_device_module);
468 AudioCodingModule::Config acm_config;
469 acm_config.decoder_factory = decoder_factory;
470 acm_config.neteq_config.codec_pair_id = codec_pair_id;
471 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
472 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100473 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200474 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100475 acm_config.neteq_config.enable_rtx_handling =
476 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200477 audio_coding_.reset(AudioCodingModule::Create(acm_config));
478
479 _outputAudioLevel.Clear();
480
481 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
482 RtpRtcp::Configuration configuration;
483 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100484 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200485 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200486 configuration.receive_statistics = rtp_receive_statistics_.get();
487
488 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200489
490 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
491 _rtpRtcpModule->SetSendingMediaStatus(false);
492 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200493
Niels Möller530ead42018-10-04 14:28:39 +0200494 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
495
Niels Möller530ead42018-10-04 14:28:39 +0200496 // Ensure that RTCP is enabled by default for the created channel.
497 // Note that, the module will keep generating RTCP until it is explicitly
498 // disabled by the user.
499 // After StopListen (when no sockets exists), RTCP packets will no longer
500 // be transmitted since the Transport object will then be invalid.
501 // RTCP is enabled by default.
502 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200503
504 if (media_transport_) {
505 media_transport_->SetReceiveAudioSink(this);
506 }
Niels Möller530ead42018-10-04 14:28:39 +0200507}
508
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100509ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200510 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200511
512 if (media_transport_) {
513 media_transport_->SetReceiveAudioSink(nullptr);
514 }
515
Niels Möller530ead42018-10-04 14:28:39 +0200516 StopPlayout();
517
Niels Möller530ead42018-10-04 14:28:39 +0200518 int error = audio_coding_->RegisterTransportCallback(NULL);
519 RTC_DCHECK_EQ(0, error);
520
Niels Möller530ead42018-10-04 14:28:39 +0200521 if (_moduleProcessThreadPtr)
522 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200523}
524
525void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100526 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200527 rtc::CritScope cs(&_callbackCritSect);
528 audio_sink_ = sink;
529}
530
Niels Möller80c67622018-11-12 13:22:47 +0100531void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100532 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100533 rtc::CritScope lock(&playing_lock_);
534 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200535}
536
Niels Möller80c67622018-11-12 13:22:47 +0100537void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100538 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100539 rtc::CritScope lock(&playing_lock_);
540 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200541 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200542}
543
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100544absl::optional<std::pair<int, SdpAudioFormat>>
545 ChannelReceive::GetReceiveCodec() const {
Niels Möller349ade32018-11-16 09:50:42 +0100546 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100547 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200548}
549
550std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100551 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200552 int64_t now_ms = rtc::TimeMillis();
553 std::vector<RtpSource> sources;
554 {
555 rtc::CritScope cs(&rtp_sources_lock_);
556 sources = contributing_sources_.GetSources(now_ms);
557 if (last_received_rtp_system_time_ms_ >=
558 now_ms - ContributingSources::kHistoryMs) {
559 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
560 RtpSourceType::SSRC);
561 sources.back().set_audio_level(last_received_rtp_audio_level_);
562 }
563 }
564 return sources;
565}
566
567void ChannelReceive::SetReceiveCodecs(
568 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100569 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200570 for (const auto& kv : codecs) {
571 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
572 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
573 }
574 audio_coding_->SetReceiveCodecs(codecs);
575}
576
Niels Möller349ade32018-11-16 09:50:42 +0100577// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200578void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
579 int64_t now_ms = rtc::TimeMillis();
580 uint8_t audio_level;
581 bool voice_activity;
582 bool has_audio_level =
583 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
584
585 {
586 rtc::CritScope cs(&rtp_sources_lock_);
587 last_received_rtp_timestamp_ = packet.Timestamp();
588 last_received_rtp_system_time_ms_ = now_ms;
589 if (has_audio_level)
590 last_received_rtp_audio_level_ = audio_level;
591 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100592 contributing_sources_.Update(
593 now_ms, csrcs,
594 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200595 }
596
597 // Store playout timestamp for the received RTP packet
598 UpdatePlayoutTimestamp(false);
599
600 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
601 if (it == payload_type_frequencies_.end())
602 return;
603 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
604 RtpPacketReceived packet_copy(packet);
605 packet_copy.set_payload_type_frequency(it->second);
606
607 rtp_receive_statistics_->OnRtpPacket(packet_copy);
608
609 RTPHeader header;
610 packet_copy.GetHeader(&header);
611
612 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
613}
614
615bool ChannelReceive::ReceivePacket(const uint8_t* packet,
616 size_t packet_length,
617 const RTPHeader& header) {
618 const uint8_t* payload = packet + header.headerLength;
619 assert(packet_length >= header.headerLength);
620 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200621
Benjamin Wright84583f62018-10-04 14:22:34 -0700622 size_t payload_data_length = payload_length - header.paddingLength;
623
624 // E2EE Custom Audio Frame Decryption (This is optional).
625 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
626 rtc::Buffer decrypted_audio_payload;
627 if (frame_decryptor_ != nullptr) {
628 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
629 cricket::MEDIA_TYPE_AUDIO, payload_length);
630 decrypted_audio_payload.SetSize(max_plaintext_size);
631
632 size_t bytes_written = 0;
633 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
634 header.arrOfCSRCs + header.numCSRCs);
635 int decrypt_status = frame_decryptor_->Decrypt(
636 cricket::MEDIA_TYPE_AUDIO, csrcs,
637 /*additional_data=*/nullptr,
638 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
639 decrypted_audio_payload, &bytes_written);
640
641 // In this case just interpret the failure as a silent frame.
642 if (decrypt_status != 0) {
643 bytes_written = 0;
644 }
645
646 // Resize the decrypted audio payload to the number of bytes actually
647 // written.
648 decrypted_audio_payload.SetSize(bytes_written);
649 // Update the final payload.
650 payload = decrypted_audio_payload.data();
651 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700652 } else if (crypto_options_.sframe.require_frame_encryption) {
653 RTC_DLOG(LS_ERROR)
654 << "FrameDecryptor required but not set, dropping packet";
655 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700656 }
657
Niels Möller530ead42018-10-04 14:28:39 +0200658 if (payload_data_length == 0) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100659 return OnReceivedPayloadData(nullptr, 0, header);
Niels Möller530ead42018-10-04 14:28:39 +0200660 }
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100661 return OnReceivedPayloadData(payload, payload_data_length, header);
Niels Möller530ead42018-10-04 14:28:39 +0200662}
663
Niels Möller349ade32018-11-16 09:50:42 +0100664// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100665// TODO(nisse): Drop always-true return value.
666bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200667 // Store playout timestamp for the received RTCP packet
668 UpdatePlayoutTimestamp(true);
669
670 // Deliver RTCP packet to RTP/RTCP module for parsing
671 _rtpRtcpModule->IncomingRtcpPacket(data, length);
672
673 int64_t rtt = GetRTT();
674 if (rtt == 0) {
675 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100676 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200677 }
678
Niels Möller530ead42018-10-04 14:28:39 +0200679 uint32_t ntp_secs = 0;
680 uint32_t ntp_frac = 0;
681 uint32_t rtp_timestamp = 0;
682 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
683 &rtp_timestamp)) {
684 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100685 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200686 }
687
688 {
689 rtc::CritScope lock(&ts_stats_lock_);
690 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
691 }
Niels Möller80c67622018-11-12 13:22:47 +0100692 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200693}
694
695int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100696 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200697 return _outputAudioLevel.LevelFullRange();
698}
699
700double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100701 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200702 return _outputAudioLevel.TotalEnergy();
703}
704
705double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100706 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200707 return _outputAudioLevel.TotalDuration();
708}
709
710void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100711 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200712 rtc::CritScope cs(&volume_settings_critsect_);
713 _outputGain = scaling;
714}
715
Niels Möller349ade32018-11-16 09:50:42 +0100716void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
717 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200718 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200719}
720
Niels Möller530ead42018-10-04 14:28:39 +0200721void ChannelReceive::RegisterReceiverCongestionControlObjects(
722 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100723 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200724 RTC_DCHECK(packet_router);
725 RTC_DCHECK(!packet_router_);
726 constexpr bool remb_candidate = false;
727 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
728 packet_router_ = packet_router;
729}
730
731void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100732 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200733 RTC_DCHECK(packet_router_);
734 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
735 packet_router_ = nullptr;
736}
737
Niels Möller349ade32018-11-16 09:50:42 +0100738CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
739 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200740 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100741 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200742
743 // The jitter statistics is updated for each received RTP packet and is
744 // based on received packets.
745 RtcpStatistics statistics;
746 StreamStatistician* statistician =
747 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
748 if (statistician) {
749 statistician->GetStatistics(&statistics,
750 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
751 }
752
753 stats.fractionLost = statistics.fraction_lost;
754 stats.cumulativeLost = statistics.packets_lost;
755 stats.extendedMax = statistics.extended_highest_sequence_number;
756 stats.jitterSamples = statistics.jitter;
757
758 // --- RTT
759 stats.rttMs = GetRTT();
760
761 // --- Data counters
762
763 size_t bytesReceived(0);
764 uint32_t packetsReceived(0);
765
766 if (statistician) {
767 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
768 }
769
770 stats.bytesReceived = bytesReceived;
771 stats.packetsReceived = packetsReceived;
772
773 // --- Timestamps
774 {
775 rtc::CritScope lock(&ts_stats_lock_);
776 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
777 }
Niels Möller80c67622018-11-12 13:22:47 +0100778 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200779}
780
Niels Möller349ade32018-11-16 09:50:42 +0100781void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
782 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200783 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100784 if (enable) {
785 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100786 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100787 } else {
788 rtp_receive_statistics_->SetMaxReorderingThreshold(
789 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200790 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100791 }
Niels Möller530ead42018-10-04 14:28:39 +0200792}
793
794// Called when we are missing one or more packets.
795int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
796 int length) {
797 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
798}
799
Niels Möllerdced9f62018-11-19 10:27:07 +0100800void ChannelReceive::SetAssociatedSendChannel(
801 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100802 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200803 rtc::CritScope lock(&assoc_send_channel_lock_);
804 associated_send_channel_ = channel;
805}
806
Niels Möller80c67622018-11-12 13:22:47 +0100807NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100808 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100809 NetworkStatistics stats;
810 int error = audio_coding_->GetNetworkStatistics(&stats);
811 RTC_DCHECK_EQ(0, error);
812 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200813}
814
Niels Möller80c67622018-11-12 13:22:47 +0100815AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100816 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100817 AudioDecodingCallStats stats;
818 audio_coding_->GetDecodingCallStatistics(&stats);
819 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200820}
821
822uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100823 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
824 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200825 rtc::CritScope lock(&video_sync_lock_);
826 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
827}
828
Niels Möller349ade32018-11-16 09:50:42 +0100829void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
830 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
831 // Limit to range accepted by both VoE and ACM, so we're at least getting as
832 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100833 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
834 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100835 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200836 RTC_DLOG(LS_ERROR)
837 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200838 }
Niels Möller530ead42018-10-04 14:28:39 +0200839}
840
Niels Möller349ade32018-11-16 09:50:42 +0100841uint32_t ChannelReceive::GetPlayoutTimestamp() const {
842 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200843 {
844 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100845 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200846 }
Niels Möller530ead42018-10-04 14:28:39 +0200847}
848
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100849bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
850 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
851}
852
853int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
854 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
855}
856
Niels Möller530ead42018-10-04 14:28:39 +0200857absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100858 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200859 Syncable::Info info;
860 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
861 &info.capture_time_ntp_frac, nullptr, nullptr,
862 &info.capture_time_source_clock) != 0) {
863 return absl::nullopt;
864 }
865 {
866 rtc::CritScope cs(&rtp_sources_lock_);
867 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
868 return absl::nullopt;
869 }
870 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
871 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
872 }
873 return info;
874}
875
876void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
877 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
878
879 if (!jitter_buffer_playout_timestamp_) {
880 // This can happen if this channel has not received any RTP packets. In
881 // this case, NetEq is not capable of computing a playout timestamp.
882 return;
883 }
884
885 uint16_t delay_ms = 0;
886 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
887 RTC_DLOG(LS_WARNING)
888 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
889 << " playout delay from the ADM";
890 return;
891 }
892
893 RTC_DCHECK(jitter_buffer_playout_timestamp_);
894 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
895
896 // Remove the playout delay.
897 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
898
899 {
900 rtc::CritScope lock(&video_sync_lock_);
901 if (!rtcp) {
902 playout_timestamp_rtp_ = playout_timestamp;
903 }
904 playout_delay_ms_ = delay_ms;
905 }
906}
907
908int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100909 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200910 // Default to the playout frequency if we've not gotten any packets yet.
911 // TODO(ossu): Zero clockrate can only happen if we've added an external
912 // decoder for a format we don't support internally. Remove once that way of
913 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100914 return (decoder && decoder->second.clockrate_hz != 0)
915 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200916 : audio_coding_->PlayoutFrequency();
917}
918
919int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800920 if (media_transport_) {
921 auto target_rate = media_transport_->GetLatestTargetTransferRate();
922 if (target_rate.has_value()) {
923 return target_rate->network_estimate.round_trip_time.ms();
924 }
925
926 return 0;
927 }
Niels Möller530ead42018-10-04 14:28:39 +0200928 RtcpMode method = _rtpRtcpModule->RTCP();
929 if (method == RtcpMode::kOff) {
930 return 0;
931 }
932 std::vector<RTCPReportBlock> report_blocks;
933 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
934
935 // TODO(nisse): Could we check the return value from the ->RTT() call below,
936 // instead of checking if we have any report blocks?
937 if (report_blocks.empty()) {
938 rtc::CritScope lock(&assoc_send_channel_lock_);
939 // Tries to get RTT from an associated channel.
940 if (!associated_send_channel_) {
941 return 0;
942 }
943 return associated_send_channel_->GetRTT();
944 }
945
946 int64_t rtt = 0;
947 int64_t avg_rtt = 0;
948 int64_t max_rtt = 0;
949 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100950 // TODO(nisse): This method computes RTT based on sender reports, even though
951 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200952 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
953 0) {
954 return 0;
955 }
956 return rtt;
957}
958
Niels Möller349ade32018-11-16 09:50:42 +0100959} // namespace
960
961std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
962 ProcessThread* module_process_thread,
963 AudioDeviceModule* audio_device_module,
964 MediaTransportInterface* media_transport,
965 Transport* rtcp_send_transport,
966 RtcEventLog* rtc_event_log,
967 uint32_t remote_ssrc,
968 size_t jitter_buffer_max_packets,
969 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100970 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100971 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100972 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
973 absl::optional<AudioCodecPairId> codec_pair_id,
974 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
975 const webrtc::CryptoOptions& crypto_options) {
976 return absl::make_unique<ChannelReceive>(
977 module_process_thread, audio_device_module, media_transport,
978 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100979 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100980 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
981 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100982}
983
Niels Möller530ead42018-10-04 14:28:39 +0200984} // namespace voe
985} // namespace webrtc