blob: f65d125cde3bbe1286a083bc4785b948bb6e99a6 [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.
Sebastian Jansson977b3352019-03-04 17:43:34 +010079 ChannelReceive(Clock* clock,
80 ProcessThread* module_process_thread,
Niels Möller349ade32018-11-16 09:50:42 +010081 AudioDeviceModule* audio_device_module,
82 MediaTransportInterface* media_transport,
83 Transport* rtcp_send_transport,
84 RtcEventLog* rtc_event_log,
85 uint32_t remote_ssrc,
86 size_t jitter_buffer_max_packets,
87 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010088 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +010089 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +010090 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
91 absl::optional<AudioCodecPairId> codec_pair_id,
92 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
93 const webrtc::CryptoOptions& crypto_options);
94 ~ChannelReceive() override;
95
96 void SetSink(AudioSinkInterface* sink) override;
97
98 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
99
100 // API methods
101
102 void StartPlayout() override;
103 void StopPlayout() override;
104
105 // Codecs
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000106 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
107 const override;
Niels Möller349ade32018-11-16 09:50:42 +0100108
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100109 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möller349ade32018-11-16 09:50:42 +0100110
111 // RtpPacketSinkInterface.
112 void OnRtpPacket(const RtpPacketReceived& packet) override;
113
114 // Muting, Volume and Level.
115 void SetChannelOutputVolumeScaling(float scaling) override;
116 int GetSpeechOutputLevelFullRange() const override;
117 // See description of "totalAudioEnergy" in the WebRTC stats spec:
118 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
119 double GetTotalOutputEnergy() const override;
120 double GetTotalOutputDuration() const override;
121
122 // Stats.
123 NetworkStatistics GetNetworkStatistics() const override;
124 AudioDecodingCallStats GetDecodingCallStatistics() const override;
125
126 // Audio+Video Sync.
127 uint32_t GetDelayEstimate() const override;
128 void SetMinimumPlayoutDelay(int delayMs) override;
129 uint32_t GetPlayoutTimestamp() const override;
130
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100131 // Audio quality.
132 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
133 int GetBaseMinimumPlayoutDelayMs() const override;
134
Niels Möller349ade32018-11-16 09:50:42 +0100135 // Produces the transport-related timestamps; current_delay_ms is left unset.
136 absl::optional<Syncable::Info> GetSyncInfo() const override;
137
138 // RTP+RTCP
139 void SetLocalSSRC(unsigned int ssrc) override;
140
141 void RegisterReceiverCongestionControlObjects(
142 PacketRouter* packet_router) override;
143 void ResetReceiverCongestionControlObjects() override;
144
145 CallReceiveStatistics GetRTCPStatistics() const override;
146 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
147
148 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
149 int sample_rate_hz,
150 AudioFrame* audio_frame) override;
151
152 int PreferredSampleRate() const override;
153
154 // Associate to a send channel.
155 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100156 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100157
158 std::vector<RtpSource> GetSources() const override;
159
160 private:
Niels Möller349ade32018-11-16 09:50:42 +0100161 bool ReceivePacket(const uint8_t* packet,
162 size_t packet_length,
163 const RTPHeader& header);
164 int ResendPackets(const uint16_t* sequence_numbers, int length);
165 void UpdatePlayoutTimestamp(bool rtcp);
166
167 int GetRtpTimestampRateHz() const;
168 int64_t GetRTT() const;
169
170 // MediaTransportAudioSinkInterface override;
Sergey Silkine049eba2019-02-18 09:52:26 +0000171 void OnData(uint64_t channel_id,
172 MediaTransportEncodedAudioFrame frame) override;
Niels Möller349ade32018-11-16 09:50:42 +0100173
174 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
175 size_t payloadSize,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100176 const RTPHeader& rtpHeader);
Niels Möller349ade32018-11-16 09:50:42 +0100177
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100178 bool Playing() const {
179 rtc::CritScope lock(&playing_lock_);
180 return playing_;
181 }
182
Niels Möller349ade32018-11-16 09:50:42 +0100183 // Thread checkers document and lock usage of some methods to specific threads
184 // we know about. The goal is to eventually split up voe::ChannelReceive into
185 // parts with single-threaded semantics, and thereby reduce the need for
186 // locks.
187 rtc::ThreadChecker worker_thread_checker_;
188 rtc::ThreadChecker module_process_thread_checker_;
189 // Methods accessed from audio and video threads are checked for sequential-
190 // only access. We don't necessarily own and control these threads, so thread
191 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
192 // audio thread to another, but access is still sequential.
193 rtc::RaceChecker audio_thread_race_checker_;
194 rtc::RaceChecker video_capture_thread_race_checker_;
195 rtc::CriticalSection _callbackCritSect;
196 rtc::CriticalSection volume_settings_critsect_;
197
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100198 rtc::CriticalSection playing_lock_;
199 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100200
201 RtcEventLog* const event_log_;
202
203 // Indexed by payload type.
204 std::map<uint8_t, int> payload_type_frequencies_;
205
206 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
207 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
208 const uint32_t remote_ssrc_;
209
210 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
211 // queried on the worker thread.
212 rtc::CriticalSection rtp_sources_lock_;
213 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
214 absl::optional<uint32_t> last_received_rtp_timestamp_
215 RTC_GUARDED_BY(&rtp_sources_lock_);
216 absl::optional<int64_t> last_received_rtp_system_time_ms_
217 RTC_GUARDED_BY(&rtp_sources_lock_);
218 absl::optional<uint8_t> last_received_rtp_audio_level_
219 RTC_GUARDED_BY(&rtp_sources_lock_);
220
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
257 MediaTransportInterface* const media_transport_;
258
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.
268 RTC_CHECK(!media_transport_);
269
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) {
Niels Möller7d76a312018-10-26 12:57:07 +0200299 RTC_CHECK(media_transport_);
300
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,
Niels Möller7d76a312018-10-26 12:57:07 +0200435 MediaTransportInterface* media_transport,
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),
Niels Möller7d76a312018-10-26 12:57:07 +0200461 media_transport_(media_transport),
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
506 if (media_transport_) {
507 media_transport_->SetReceiveAudioSink(this);
508 }
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
514 if (media_transport_) {
515 media_transport_->SetReceiveAudioSink(nullptr);
516 }
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
552std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200553 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200554 int64_t now_ms = rtc::TimeMillis();
555 std::vector<RtpSource> sources;
556 {
557 rtc::CritScope cs(&rtp_sources_lock_);
558 sources = contributing_sources_.GetSources(now_ms);
559 if (last_received_rtp_system_time_ms_ >=
560 now_ms - ContributingSources::kHistoryMs) {
561 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
562 RtpSourceType::SSRC);
563 sources.back().set_audio_level(last_received_rtp_audio_level_);
564 }
565 }
566 return sources;
567}
568
569void ChannelReceive::SetReceiveCodecs(
570 const std::map<int, SdpAudioFormat>& codecs) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200571 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200572 for (const auto& kv : codecs) {
573 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
574 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
575 }
576 audio_coding_->SetReceiveCodecs(codecs);
577}
578
Niels Möller349ade32018-11-16 09:50:42 +0100579// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200580void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
581 int64_t now_ms = rtc::TimeMillis();
582 uint8_t audio_level;
583 bool voice_activity;
584 bool has_audio_level =
585 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
586
587 {
588 rtc::CritScope cs(&rtp_sources_lock_);
589 last_received_rtp_timestamp_ = packet.Timestamp();
590 last_received_rtp_system_time_ms_ = now_ms;
591 if (has_audio_level)
592 last_received_rtp_audio_level_ = audio_level;
593 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100594 contributing_sources_.Update(
595 now_ms, csrcs,
596 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200597 }
598
599 // Store playout timestamp for the received RTP packet
600 UpdatePlayoutTimestamp(false);
601
602 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
603 if (it == payload_type_frequencies_.end())
604 return;
605 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
606 RtpPacketReceived packet_copy(packet);
607 packet_copy.set_payload_type_frequency(it->second);
608
609 rtp_receive_statistics_->OnRtpPacket(packet_copy);
610
611 RTPHeader header;
612 packet_copy.GetHeader(&header);
613
614 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
615}
616
617bool ChannelReceive::ReceivePacket(const uint8_t* packet,
618 size_t packet_length,
619 const RTPHeader& header) {
620 const uint8_t* payload = packet + header.headerLength;
621 assert(packet_length >= header.headerLength);
622 size_t payload_length = packet_length - header.headerLength;
Niels Möller530ead42018-10-04 14:28:39 +0200623
Benjamin Wright84583f62018-10-04 14:22:34 -0700624 size_t payload_data_length = payload_length - header.paddingLength;
625
626 // E2EE Custom Audio Frame Decryption (This is optional).
627 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
628 rtc::Buffer decrypted_audio_payload;
629 if (frame_decryptor_ != nullptr) {
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000630 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
Benjamin Wright84583f62018-10-04 14:22:34 -0700631 cricket::MEDIA_TYPE_AUDIO, payload_length);
632 decrypted_audio_payload.SetSize(max_plaintext_size);
633
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000634 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
635 header.arrOfCSRCs + header.numCSRCs);
636 const FrameDecryptorInterface::Result decrypt_result =
637 frame_decryptor_->Decrypt(
638 cricket::MEDIA_TYPE_AUDIO, csrcs,
639 /*additional_data=*/nullptr,
640 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
641 decrypted_audio_payload);
Benjamin Wright84583f62018-10-04 14:22:34 -0700642
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000643 if (decrypt_result.IsOk()) {
644 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
645 } else {
646 // Interpret failures as a silent frame.
647 decrypted_audio_payload.SetSize(0);
Benjamin Wright84583f62018-10-04 14:22:34 -0700648 }
649
Benjamin Wright84583f62018-10-04 14:22:34 -0700650 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öller8fb1a6a2019-03-05 14:29:42 +0100665void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200666 // Store playout timestamp for the received RTCP packet
667 UpdatePlayoutTimestamp(true);
668
669 // Deliver RTCP packet to RTP/RTCP module for parsing
670 _rtpRtcpModule->IncomingRtcpPacket(data, length);
671
672 int64_t rtt = GetRTT();
673 if (rtt == 0) {
674 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100675 return;
Niels Möller530ead42018-10-04 14:28:39 +0200676 }
677
Niels Möller530ead42018-10-04 14:28:39 +0200678 uint32_t ntp_secs = 0;
679 uint32_t ntp_frac = 0;
680 uint32_t rtp_timestamp = 0;
681 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
682 &rtp_timestamp)) {
683 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100684 return;
Niels Möller530ead42018-10-04 14:28:39 +0200685 }
686
687 {
688 rtc::CritScope lock(&ts_stats_lock_);
689 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
690 }
Niels Möller530ead42018-10-04 14:28:39 +0200691}
692
693int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200694 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200695 return _outputAudioLevel.LevelFullRange();
696}
697
698double ChannelReceive::GetTotalOutputEnergy() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200699 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200700 return _outputAudioLevel.TotalEnergy();
701}
702
703double ChannelReceive::GetTotalOutputDuration() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200704 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200705 return _outputAudioLevel.TotalDuration();
706}
707
708void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200709 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200710 rtc::CritScope cs(&volume_settings_critsect_);
711 _outputGain = scaling;
712}
713
Niels Möller349ade32018-11-16 09:50:42 +0100714void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200715 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200716 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200717}
718
Niels Möller530ead42018-10-04 14:28:39 +0200719void ChannelReceive::RegisterReceiverCongestionControlObjects(
720 PacketRouter* packet_router) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200721 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200722 RTC_DCHECK(packet_router);
723 RTC_DCHECK(!packet_router_);
724 constexpr bool remb_candidate = false;
725 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
726 packet_router_ = packet_router;
727}
728
729void ChannelReceive::ResetReceiverCongestionControlObjects() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200730 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200731 RTC_DCHECK(packet_router_);
732 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
733 packet_router_ = nullptr;
734}
735
Niels Möller349ade32018-11-16 09:50:42 +0100736CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200737 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200738 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100739 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200740
741 // The jitter statistics is updated for each received RTP packet and is
742 // based on received packets.
743 RtcpStatistics statistics;
744 StreamStatistician* statistician =
745 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
746 if (statistician) {
747 statistician->GetStatistics(&statistics,
748 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
749 }
750
751 stats.fractionLost = statistics.fraction_lost;
752 stats.cumulativeLost = statistics.packets_lost;
753 stats.extendedMax = statistics.extended_highest_sequence_number;
754 stats.jitterSamples = statistics.jitter;
755
756 // --- RTT
757 stats.rttMs = GetRTT();
758
759 // --- Data counters
Niels Möller530ead42018-10-04 14:28:39 +0200760 if (statistician) {
Henrik Boström01738c62019-04-15 17:32:00 +0200761 StreamDataCounters data_counters;
762 statistician->GetReceiveStreamDataCounters(&data_counters);
763 // TODO(http://crbug.com/webrtc/10525): Bytes received should only include
764 // payload bytes, not header and padding bytes.
765 stats.bytesReceived = data_counters.transmitted.payload_bytes +
766 data_counters.transmitted.header_bytes +
767 data_counters.transmitted.padding_bytes;
768 stats.packetsReceived = data_counters.transmitted.packets;
769 stats.last_packet_received_timestamp_ms =
770 data_counters.last_packet_received_timestamp_ms;
771 } else {
772 stats.bytesReceived = 0;
773 stats.packetsReceived = 0;
774 stats.last_packet_received_timestamp_ms = absl::nullopt;
Niels Möller530ead42018-10-04 14:28:39 +0200775 }
776
Niels Möller530ead42018-10-04 14:28:39 +0200777 // --- Timestamps
778 {
779 rtc::CritScope lock(&ts_stats_lock_);
780 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
781 }
Niels Möller80c67622018-11-12 13:22:47 +0100782 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200783}
784
Niels Möller349ade32018-11-16 09:50:42 +0100785void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200786 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200787 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100788 if (enable) {
789 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100790 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100791 } else {
792 rtp_receive_statistics_->SetMaxReorderingThreshold(
793 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200794 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100795 }
Niels Möller530ead42018-10-04 14:28:39 +0200796}
797
798// Called when we are missing one or more packets.
799int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
800 int length) {
801 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
802}
803
Niels Möllerdced9f62018-11-19 10:27:07 +0100804void ChannelReceive::SetAssociatedSendChannel(
805 const ChannelSendInterface* channel) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200806 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200807 rtc::CritScope lock(&assoc_send_channel_lock_);
808 associated_send_channel_ = channel;
809}
810
Niels Möller80c67622018-11-12 13:22:47 +0100811NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200812 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100813 NetworkStatistics stats;
814 int error = audio_coding_->GetNetworkStatistics(&stats);
815 RTC_DCHECK_EQ(0, error);
816 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200817}
818
Niels Möller80c67622018-11-12 13:22:47 +0100819AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200820 RTC_DCHECK(worker_thread_checker_.IsCurrent());
Niels Möller80c67622018-11-12 13:22:47 +0100821 AudioDecodingCallStats stats;
822 audio_coding_->GetDecodingCallStatistics(&stats);
823 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200824}
825
826uint32_t ChannelReceive::GetDelayEstimate() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200827 RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
828 module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200829 rtc::CritScope lock(&video_sync_lock_);
830 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
831}
832
Niels Möller349ade32018-11-16 09:50:42 +0100833void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200834 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller349ade32018-11-16 09:50:42 +0100835 // Limit to range accepted by both VoE and ACM, so we're at least getting as
836 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100837 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
838 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100839 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200840 RTC_DLOG(LS_ERROR)
841 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200842 }
Niels Möller530ead42018-10-04 14:28:39 +0200843}
844
Niels Möller349ade32018-11-16 09:50:42 +0100845uint32_t ChannelReceive::GetPlayoutTimestamp() const {
846 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200847 {
848 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100849 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200850 }
Niels Möller530ead42018-10-04 14:28:39 +0200851}
852
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100853bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
854 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
855}
856
857int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
858 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
859}
860
Niels Möller530ead42018-10-04 14:28:39 +0200861absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200862 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200863 Syncable::Info info;
864 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
865 &info.capture_time_ntp_frac, nullptr, nullptr,
866 &info.capture_time_source_clock) != 0) {
867 return absl::nullopt;
868 }
869 {
870 rtc::CritScope cs(&rtp_sources_lock_);
871 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
872 return absl::nullopt;
873 }
874 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
875 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
876 }
877 return info;
878}
879
880void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
881 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
882
883 if (!jitter_buffer_playout_timestamp_) {
884 // This can happen if this channel has not received any RTP packets. In
885 // this case, NetEq is not capable of computing a playout timestamp.
886 return;
887 }
888
889 uint16_t delay_ms = 0;
890 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
891 RTC_DLOG(LS_WARNING)
892 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
893 << " playout delay from the ADM";
894 return;
895 }
896
897 RTC_DCHECK(jitter_buffer_playout_timestamp_);
898 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
899
900 // Remove the playout delay.
901 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
902
903 {
904 rtc::CritScope lock(&video_sync_lock_);
905 if (!rtcp) {
906 playout_timestamp_rtp_ = playout_timestamp;
907 }
908 playout_delay_ms_ = delay_ms;
909 }
910}
911
912int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100913 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200914 // Default to the playout frequency if we've not gotten any packets yet.
915 // TODO(ossu): Zero clockrate can only happen if we've added an external
916 // decoder for a format we don't support internally. Remove once that way of
917 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100918 return (decoder && decoder->second.clockrate_hz != 0)
919 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200920 : audio_coding_->PlayoutFrequency();
921}
922
923int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800924 if (media_transport_) {
925 auto target_rate = media_transport_->GetLatestTargetTransferRate();
926 if (target_rate.has_value()) {
927 return target_rate->network_estimate.round_trip_time.ms();
928 }
929
930 return 0;
931 }
Niels Möller530ead42018-10-04 14:28:39 +0200932 RtcpMode method = _rtpRtcpModule->RTCP();
933 if (method == RtcpMode::kOff) {
934 return 0;
935 }
936 std::vector<RTCPReportBlock> report_blocks;
937 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
938
939 // TODO(nisse): Could we check the return value from the ->RTT() call below,
940 // instead of checking if we have any report blocks?
941 if (report_blocks.empty()) {
942 rtc::CritScope lock(&assoc_send_channel_lock_);
943 // Tries to get RTT from an associated channel.
944 if (!associated_send_channel_) {
945 return 0;
946 }
947 return associated_send_channel_->GetRTT();
948 }
949
950 int64_t rtt = 0;
951 int64_t avg_rtt = 0;
952 int64_t max_rtt = 0;
953 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100954 // TODO(nisse): This method computes RTT based on sender reports, even though
955 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200956 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
957 0) {
958 return 0;
959 }
960 return rtt;
961}
962
Niels Möller349ade32018-11-16 09:50:42 +0100963} // namespace
964
965std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100966 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100967 ProcessThread* module_process_thread,
968 AudioDeviceModule* audio_device_module,
969 MediaTransportInterface* media_transport,
970 Transport* rtcp_send_transport,
971 RtcEventLog* rtc_event_log,
972 uint32_t remote_ssrc,
973 size_t jitter_buffer_max_packets,
974 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100975 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100976 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100977 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
978 absl::optional<AudioCodecPairId> codec_pair_id,
979 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
980 const webrtc::CryptoOptions& crypto_options) {
981 return absl::make_unique<ChannelReceive>(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100982 clock, module_process_thread, audio_device_module, media_transport,
Niels Möller349ade32018-11-16 09:50:42 +0100983 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100984 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100985 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
986 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100987}
988
Niels Möller530ead42018-10-04 14:28:39 +0200989} // namespace voe
990} // namespace webrtc