blob: 679666e3e1fdcfd868a603c5240c8603d6fdfbbe [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
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100106 absl::optional<std::pair<int, SdpAudioFormat>>
107 GetReceiveCodec() 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?
465 module_process_thread_checker_.DetachFromThread();
466
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
492 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
493 _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() {
Niels Möller530ead42018-10-04 14:28:39 +0200512 RTC_DCHECK(construction_thread_.CalledOnValidThread());
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) {
Niels Möller349ade32018-11-16 09:50:42 +0100528 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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() {
Niels Möller349ade32018-11-16 09:50:42 +0100534 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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() {
Niels Möller349ade32018-11-16 09:50:42 +0100540 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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 {
Niels Möller349ade32018-11-16 09:50:42 +0100548 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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 {
Niels Möller349ade32018-11-16 09:50:42 +0100553 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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) {
Niels Möller349ade32018-11-16 09:50:42 +0100571 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
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) {
630 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
631 cricket::MEDIA_TYPE_AUDIO, payload_length);
632 decrypted_audio_payload.SetSize(max_plaintext_size);
633
634 size_t bytes_written = 0;
635 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
636 header.arrOfCSRCs + header.numCSRCs);
637 int decrypt_status = 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, &bytes_written);
642
643 // In this case just interpret the failure as a silent frame.
644 if (decrypt_status != 0) {
645 bytes_written = 0;
646 }
647
648 // Resize the decrypted audio payload to the number of bytes actually
649 // written.
650 decrypted_audio_payload.SetSize(bytes_written);
651 // Update the final payload.
652 payload = decrypted_audio_payload.data();
653 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700654 } else if (crypto_options_.sframe.require_frame_encryption) {
655 RTC_DLOG(LS_ERROR)
656 << "FrameDecryptor required but not set, dropping packet";
657 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700658 }
659
Niels Möller530ead42018-10-04 14:28:39 +0200660 if (payload_data_length == 0) {
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100661 return OnReceivedPayloadData(nullptr, 0, header);
Niels Möller530ead42018-10-04 14:28:39 +0200662 }
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100663 return OnReceivedPayloadData(payload, payload_data_length, header);
Niels Möller530ead42018-10-04 14:28:39 +0200664}
665
Niels Möller349ade32018-11-16 09:50:42 +0100666// May be called on either worker thread or network thread.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100667void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200668 // Store playout timestamp for the received RTCP packet
669 UpdatePlayoutTimestamp(true);
670
671 // Deliver RTCP packet to RTP/RTCP module for parsing
672 _rtpRtcpModule->IncomingRtcpPacket(data, length);
673
674 int64_t rtt = GetRTT();
675 if (rtt == 0) {
676 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100677 return;
Niels Möller530ead42018-10-04 14:28:39 +0200678 }
679
Niels Möller530ead42018-10-04 14:28:39 +0200680 uint32_t ntp_secs = 0;
681 uint32_t ntp_frac = 0;
682 uint32_t rtp_timestamp = 0;
683 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
684 &rtp_timestamp)) {
685 // Waiting for RTCP.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100686 return;
Niels Möller530ead42018-10-04 14:28:39 +0200687 }
688
689 {
690 rtc::CritScope lock(&ts_stats_lock_);
691 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
692 }
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(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100962 Clock* clock,
Niels Möller349ade32018-11-16 09:50:42 +0100963 ProcessThread* module_process_thread,
964 AudioDeviceModule* audio_device_module,
965 MediaTransportInterface* media_transport,
966 Transport* rtcp_send_transport,
967 RtcEventLog* rtc_event_log,
968 uint32_t remote_ssrc,
969 size_t jitter_buffer_max_packets,
970 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100971 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100972 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100973 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
974 absl::optional<AudioCodecPairId> codec_pair_id,
975 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
976 const webrtc::CryptoOptions& crypto_options) {
977 return absl::make_unique<ChannelReceive>(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100978 clock, module_process_thread, audio_device_module, media_transport,
Niels Möller349ade32018-11-16 09:50:42 +0100979 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100980 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100981 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
982 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100983}
984
Niels Möller530ead42018-10-04 14:28:39 +0200985} // namespace voe
986} // namespace webrtc