blob: bfa85c00451ddd85b4ce4cfbe1e1751787323463 [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;
55constexpr int64_t kMaxRetransmissionWindowMs = 1000;
56constexpr int64_t kMinRetransmissionWindowMs = 30;
57
58// Video Sync.
59constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
60constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
61
Niels Möller7d76a312018-10-26 12:57:07 +020062webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
63 MediaTransportEncodedAudioFrame::FrameType frame_type) {
64 switch (frame_type) {
65 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
66 return kAudioFrameSpeech;
67 break;
68
69 case MediaTransportEncodedAudioFrame::FrameType::
70 kDiscountinuousTransmission:
71 return kAudioFrameCN;
72 break;
73 }
74}
75
76WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
77 const MediaTransportEncodedAudioFrame& frame,
78 uint64_t channel_id) {
79 webrtc::WebRtcRTPHeader webrtc_header = {};
80 webrtc_header.header.payloadType = frame.payload_type();
81 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
82 webrtc_header.header.timestamp = frame.starting_sample_index();
83 webrtc_header.header.sequenceNumber = frame.sequence_number();
84
85 webrtc_header.frameType =
86 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
87
88 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
89
90 // The rest are initialized by the RTPHeader constructor.
91 return webrtc_header;
92}
93
Niels Möller349ade32018-11-16 09:50:42 +010094class ChannelReceive : public ChannelReceiveInterface,
95 public MediaTransportAudioSinkInterface {
96 public:
97 // Used for receive streams.
98 ChannelReceive(ProcessThread* module_process_thread,
99 AudioDeviceModule* audio_device_module,
100 MediaTransportInterface* media_transport,
101 Transport* rtcp_send_transport,
102 RtcEventLog* rtc_event_log,
103 uint32_t remote_ssrc,
104 size_t jitter_buffer_max_packets,
105 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100106 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100107 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100108 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
109 absl::optional<AudioCodecPairId> codec_pair_id,
110 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
111 const webrtc::CryptoOptions& crypto_options);
112 ~ChannelReceive() override;
113
114 void SetSink(AudioSinkInterface* sink) override;
115
116 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
117
118 // API methods
119
120 void StartPlayout() override;
121 void StopPlayout() override;
122
123 // Codecs
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100124 absl::optional<std::pair<int, SdpAudioFormat>>
125 GetReceiveCodec() const override;
Niels Möller349ade32018-11-16 09:50:42 +0100126
127 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
128
129 // RtpPacketSinkInterface.
130 void OnRtpPacket(const RtpPacketReceived& packet) override;
131
132 // Muting, Volume and Level.
133 void SetChannelOutputVolumeScaling(float scaling) override;
134 int GetSpeechOutputLevelFullRange() const override;
135 // See description of "totalAudioEnergy" in the WebRTC stats spec:
136 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
137 double GetTotalOutputEnergy() const override;
138 double GetTotalOutputDuration() const override;
139
140 // Stats.
141 NetworkStatistics GetNetworkStatistics() const override;
142 AudioDecodingCallStats GetDecodingCallStatistics() const override;
143
144 // Audio+Video Sync.
145 uint32_t GetDelayEstimate() const override;
146 void SetMinimumPlayoutDelay(int delayMs) override;
147 uint32_t GetPlayoutTimestamp() const override;
148
149 // Produces the transport-related timestamps; current_delay_ms is left unset.
150 absl::optional<Syncable::Info> GetSyncInfo() const override;
151
152 // RTP+RTCP
153 void SetLocalSSRC(unsigned int ssrc) override;
154
155 void RegisterReceiverCongestionControlObjects(
156 PacketRouter* packet_router) override;
157 void ResetReceiverCongestionControlObjects() override;
158
159 CallReceiveStatistics GetRTCPStatistics() const override;
160 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
161
162 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
163 int sample_rate_hz,
164 AudioFrame* audio_frame) override;
165
166 int PreferredSampleRate() const override;
167
168 // Associate to a send channel.
169 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100170 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100171
172 std::vector<RtpSource> GetSources() const override;
173
174 private:
Niels Möller349ade32018-11-16 09:50:42 +0100175 bool ReceivePacket(const uint8_t* packet,
176 size_t packet_length,
177 const RTPHeader& header);
178 int ResendPackets(const uint16_t* sequence_numbers, int length);
179 void UpdatePlayoutTimestamp(bool rtcp);
180
181 int GetRtpTimestampRateHz() const;
182 int64_t GetRTT() const;
183
184 // MediaTransportAudioSinkInterface override;
185 void OnData(uint64_t channel_id,
186 MediaTransportEncodedAudioFrame frame) override;
187
188 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
189 size_t payloadSize,
190 const WebRtcRTPHeader* rtpHeader);
191
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100192 bool Playing() const {
193 rtc::CritScope lock(&playing_lock_);
194 return playing_;
195 }
196
Niels Möller349ade32018-11-16 09:50:42 +0100197 // Thread checkers document and lock usage of some methods to specific threads
198 // we know about. The goal is to eventually split up voe::ChannelReceive into
199 // parts with single-threaded semantics, and thereby reduce the need for
200 // locks.
201 rtc::ThreadChecker worker_thread_checker_;
202 rtc::ThreadChecker module_process_thread_checker_;
203 // Methods accessed from audio and video threads are checked for sequential-
204 // only access. We don't necessarily own and control these threads, so thread
205 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
206 // audio thread to another, but access is still sequential.
207 rtc::RaceChecker audio_thread_race_checker_;
208 rtc::RaceChecker video_capture_thread_race_checker_;
209 rtc::CriticalSection _callbackCritSect;
210 rtc::CriticalSection volume_settings_critsect_;
211
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100212 rtc::CriticalSection playing_lock_;
213 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100214
215 RtcEventLog* const event_log_;
216
217 // Indexed by payload type.
218 std::map<uint8_t, int> payload_type_frequencies_;
219
220 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
221 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
222 const uint32_t remote_ssrc_;
223
224 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
225 // queried on the worker thread.
226 rtc::CriticalSection rtp_sources_lock_;
227 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
228 absl::optional<uint32_t> last_received_rtp_timestamp_
229 RTC_GUARDED_BY(&rtp_sources_lock_);
230 absl::optional<int64_t> last_received_rtp_system_time_ms_
231 RTC_GUARDED_BY(&rtp_sources_lock_);
232 absl::optional<uint8_t> last_received_rtp_audio_level_
233 RTC_GUARDED_BY(&rtp_sources_lock_);
234
235 std::unique_ptr<AudioCodingModule> audio_coding_;
236 AudioSinkInterface* audio_sink_ = nullptr;
237 AudioLevel _outputAudioLevel;
238
239 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
240
241 // Timestamp of the audio pulled from NetEq.
242 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
243
244 rtc::CriticalSection video_sync_lock_;
245 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
246 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
247
248 rtc::CriticalSection ts_stats_lock_;
249
250 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
251 // The rtp timestamp of the first played out audio frame.
252 int64_t capture_start_rtp_time_stamp_;
253 // The capture ntp time (in local timebase) of the first played out audio
254 // frame.
255 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
256
257 // uses
258 ProcessThread* _moduleProcessThreadPtr;
259 AudioDeviceModule* _audioDeviceModulePtr;
260 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
261
262 // An associated send channel.
263 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100264 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100265 RTC_GUARDED_BY(assoc_send_channel_lock_);
266
267 PacketRouter* packet_router_ = nullptr;
268
269 rtc::ThreadChecker construction_thread_;
270
271 MediaTransportInterface* const media_transport_;
272
273 // E2EE Audio Frame Decryption
274 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
275 webrtc::CryptoOptions crypto_options_;
276};
Niels Möller530ead42018-10-04 14:28:39 +0200277
Niels Möller530ead42018-10-04 14:28:39 +0200278int32_t ChannelReceive::OnReceivedPayloadData(
279 const uint8_t* payloadData,
280 size_t payloadSize,
281 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200282 // We should not be receiving any RTP packets if media_transport is set.
283 RTC_CHECK(!media_transport_);
284
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100285 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200286 // Avoid inserting into NetEQ when we are not playing. Count the
287 // packet as discarded.
288 return 0;
289 }
290
291 // Push the incoming payload (parsed and ready for decoding) into the ACM
292 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
293 0) {
294 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
295 "push data to the ACM";
296 return -1;
297 }
298
299 int64_t round_trip_time = 0;
300 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
301
302 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
303 if (!nack_list.empty()) {
304 // Can't use nack_list.data() since it's not supported by all
305 // compilers.
306 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
307 }
308 return 0;
309}
310
Niels Möller7d76a312018-10-26 12:57:07 +0200311// MediaTransportAudioSinkInterface override.
312void ChannelReceive::OnData(uint64_t channel_id,
313 MediaTransportEncodedAudioFrame frame) {
314 RTC_CHECK(media_transport_);
315
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100316 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200317 // Avoid inserting into NetEQ when we are not playing. Count the
318 // packet as discarded.
319 return;
320 }
321
322 // Send encoded audio frame to Decoder / NetEq.
323 if (audio_coding_->IncomingPacket(
324 frame.encoded_data().data(), frame.encoded_data().size(),
325 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
326 0) {
327 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
328 "push data to the ACM";
329 }
330}
331
Niels Möller530ead42018-10-04 14:28:39 +0200332AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
333 int sample_rate_hz,
334 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100335 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200336 audio_frame->sample_rate_hz_ = sample_rate_hz;
337
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100338 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
339
Niels Möller530ead42018-10-04 14:28:39 +0200340 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
341 bool muted;
342 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
343 &muted) == -1) {
344 RTC_DLOG(LS_ERROR)
345 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
346 // In all likelihood, the audio in this frame is garbage. We return an
347 // error so that the audio mixer module doesn't add it to the mix. As
348 // a result, it won't be played out and the actions skipped here are
349 // irrelevant.
350 return AudioMixer::Source::AudioFrameInfo::kError;
351 }
352
353 if (muted) {
354 // TODO(henrik.lundin): We should be able to do better than this. But we
355 // will have to go through all the cases below where the audio samples may
356 // be used, and handle the muted case in some way.
357 AudioFrameOperations::Mute(audio_frame);
358 }
359
360 {
361 // Pass the audio buffers to an optional sink callback, before applying
362 // scaling/panning, as that applies to the mix operation.
363 // External recipients of the audio (e.g. via AudioTrack), will do their
364 // own mixing/dynamic processing.
365 rtc::CritScope cs(&_callbackCritSect);
366 if (audio_sink_) {
367 AudioSinkInterface::Data data(
368 audio_frame->data(), audio_frame->samples_per_channel_,
369 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
370 audio_frame->timestamp_);
371 audio_sink_->OnData(data);
372 }
373 }
374
375 float output_gain = 1.0f;
376 {
377 rtc::CritScope cs(&volume_settings_critsect_);
378 output_gain = _outputGain;
379 }
380
381 // Output volume scaling
382 if (output_gain < 0.99f || output_gain > 1.01f) {
383 // TODO(solenberg): Combine with mute state - this can cause clicks!
384 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
385 }
386
387 // Measure audio level (0-9)
388 // TODO(henrik.lundin) Use the |muted| information here too.
389 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
390 // https://crbug.com/webrtc/7517).
391 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
392
393 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
394 // The first frame with a valid rtp timestamp.
395 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
396 }
397
398 if (capture_start_rtp_time_stamp_ >= 0) {
399 // audio_frame.timestamp_ should be valid from now on.
400
401 // Compute elapsed time.
402 int64_t unwrap_timestamp =
403 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
404 audio_frame->elapsed_time_ms_ =
405 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
406 (GetRtpTimestampRateHz() / 1000);
407
408 {
409 rtc::CritScope lock(&ts_stats_lock_);
410 // Compute ntp time.
411 audio_frame->ntp_time_ms_ =
412 ntp_estimator_.Estimate(audio_frame->timestamp_);
413 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
414 if (audio_frame->ntp_time_ms_ > 0) {
415 // Compute |capture_start_ntp_time_ms_| so that
416 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
417 capture_start_ntp_time_ms_ =
418 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
419 }
420 }
421 }
422
423 {
424 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
425 audio_coding_->TargetDelayMs());
426 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
427 rtc::CritScope lock(&video_sync_lock_);
428 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
429 jitter_buffer_delay + playout_delay_ms_);
430 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
431 jitter_buffer_delay);
432 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
433 playout_delay_ms_);
434 }
435
436 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
437 : AudioMixer::Source::AudioFrameInfo::kNormal;
438}
439
440int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100441 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200442 // Return the bigger of playout and receive frequency in the ACM.
443 return std::max(audio_coding_->ReceiveFrequency(),
444 audio_coding_->PlayoutFrequency());
445}
446
447ChannelReceive::ChannelReceive(
448 ProcessThread* module_process_thread,
449 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200450 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200451 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200452 RtcEventLog* rtc_event_log,
453 uint32_t remote_ssrc,
454 size_t jitter_buffer_max_packets,
455 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100456 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100457 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200458 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700459 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700460 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700461 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200462 : event_log_(rtc_event_log),
463 rtp_receive_statistics_(
464 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
465 remote_ssrc_(remote_ssrc),
466 _outputAudioLevel(),
467 ntp_estimator_(Clock::GetRealTimeClock()),
468 playout_timestamp_rtp_(0),
469 playout_delay_ms_(0),
470 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
471 capture_start_rtp_time_stamp_(-1),
472 capture_start_ntp_time_ms_(-1),
473 _moduleProcessThreadPtr(module_process_thread),
474 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200475 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700476 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200477 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700478 frame_decryptor_(frame_decryptor),
479 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100480 // TODO(nisse): Use _moduleProcessThreadPtr instead?
481 module_process_thread_checker_.DetachFromThread();
482
Niels Möller530ead42018-10-04 14:28:39 +0200483 RTC_DCHECK(module_process_thread);
484 RTC_DCHECK(audio_device_module);
485 AudioCodingModule::Config acm_config;
486 acm_config.decoder_factory = decoder_factory;
487 acm_config.neteq_config.codec_pair_id = codec_pair_id;
488 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
489 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100490 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200491 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100492 acm_config.neteq_config.enable_rtx_handling =
493 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200494 audio_coding_.reset(AudioCodingModule::Create(acm_config));
495
496 _outputAudioLevel.Clear();
497
498 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
499 RtpRtcp::Configuration configuration;
500 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100501 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200502 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200503 configuration.receive_statistics = rtp_receive_statistics_.get();
504
505 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200506
507 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
508 _rtpRtcpModule->SetSendingMediaStatus(false);
509 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200510
Niels Möller530ead42018-10-04 14:28:39 +0200511 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
512
Niels Möller530ead42018-10-04 14:28:39 +0200513 // Ensure that RTCP is enabled by default for the created channel.
514 // Note that, the module will keep generating RTCP until it is explicitly
515 // disabled by the user.
516 // After StopListen (when no sockets exists), RTCP packets will no longer
517 // be transmitted since the Transport object will then be invalid.
518 // RTCP is enabled by default.
519 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200520
521 if (media_transport_) {
522 media_transport_->SetReceiveAudioSink(this);
523 }
Niels Möller530ead42018-10-04 14:28:39 +0200524}
525
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100526ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200527 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200528
529 if (media_transport_) {
530 media_transport_->SetReceiveAudioSink(nullptr);
531 }
532
Niels Möller530ead42018-10-04 14:28:39 +0200533 StopPlayout();
534
Niels Möller530ead42018-10-04 14:28:39 +0200535 int error = audio_coding_->RegisterTransportCallback(NULL);
536 RTC_DCHECK_EQ(0, error);
537
Niels Möller530ead42018-10-04 14:28:39 +0200538 if (_moduleProcessThreadPtr)
539 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200540}
541
542void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100543 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200544 rtc::CritScope cs(&_callbackCritSect);
545 audio_sink_ = sink;
546}
547
Niels Möller80c67622018-11-12 13:22:47 +0100548void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100549 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100550 rtc::CritScope lock(&playing_lock_);
551 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200552}
553
Niels Möller80c67622018-11-12 13:22:47 +0100554void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100555 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100556 rtc::CritScope lock(&playing_lock_);
557 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200558 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200559}
560
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100561absl::optional<std::pair<int, SdpAudioFormat>>
562 ChannelReceive::GetReceiveCodec() const {
Niels Möller349ade32018-11-16 09:50:42 +0100563 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100564 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200565}
566
567std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100568 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200569 int64_t now_ms = rtc::TimeMillis();
570 std::vector<RtpSource> sources;
571 {
572 rtc::CritScope cs(&rtp_sources_lock_);
573 sources = contributing_sources_.GetSources(now_ms);
574 if (last_received_rtp_system_time_ms_ >=
575 now_ms - ContributingSources::kHistoryMs) {
576 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
577 RtpSourceType::SSRC);
578 sources.back().set_audio_level(last_received_rtp_audio_level_);
579 }
580 }
581 return sources;
582}
583
584void ChannelReceive::SetReceiveCodecs(
585 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100586 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200587 for (const auto& kv : codecs) {
588 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
589 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
590 }
591 audio_coding_->SetReceiveCodecs(codecs);
592}
593
Niels Möller349ade32018-11-16 09:50:42 +0100594// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200595void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
596 int64_t now_ms = rtc::TimeMillis();
597 uint8_t audio_level;
598 bool voice_activity;
599 bool has_audio_level =
600 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
601
602 {
603 rtc::CritScope cs(&rtp_sources_lock_);
604 last_received_rtp_timestamp_ = packet.Timestamp();
605 last_received_rtp_system_time_ms_ = now_ms;
606 if (has_audio_level)
607 last_received_rtp_audio_level_ = audio_level;
608 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100609 contributing_sources_.Update(
610 now_ms, csrcs,
611 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200612 }
613
614 // Store playout timestamp for the received RTP packet
615 UpdatePlayoutTimestamp(false);
616
617 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
618 if (it == payload_type_frequencies_.end())
619 return;
620 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
621 RtpPacketReceived packet_copy(packet);
622 packet_copy.set_payload_type_frequency(it->second);
623
624 rtp_receive_statistics_->OnRtpPacket(packet_copy);
625
626 RTPHeader header;
627 packet_copy.GetHeader(&header);
628
629 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
630}
631
632bool ChannelReceive::ReceivePacket(const uint8_t* packet,
633 size_t packet_length,
634 const RTPHeader& header) {
635 const uint8_t* payload = packet + header.headerLength;
636 assert(packet_length >= header.headerLength);
637 size_t payload_length = packet_length - header.headerLength;
638 WebRtcRTPHeader webrtc_rtp_header = {};
639 webrtc_rtp_header.header = header;
640
Benjamin Wright84583f62018-10-04 14:22:34 -0700641 size_t payload_data_length = payload_length - header.paddingLength;
642
643 // E2EE Custom Audio Frame Decryption (This is optional).
644 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
645 rtc::Buffer decrypted_audio_payload;
646 if (frame_decryptor_ != nullptr) {
647 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
648 cricket::MEDIA_TYPE_AUDIO, payload_length);
649 decrypted_audio_payload.SetSize(max_plaintext_size);
650
651 size_t bytes_written = 0;
652 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
653 header.arrOfCSRCs + header.numCSRCs);
654 int decrypt_status = frame_decryptor_->Decrypt(
655 cricket::MEDIA_TYPE_AUDIO, csrcs,
656 /*additional_data=*/nullptr,
657 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
658 decrypted_audio_payload, &bytes_written);
659
660 // In this case just interpret the failure as a silent frame.
661 if (decrypt_status != 0) {
662 bytes_written = 0;
663 }
664
665 // Resize the decrypted audio payload to the number of bytes actually
666 // written.
667 decrypted_audio_payload.SetSize(bytes_written);
668 // Update the final payload.
669 payload = decrypted_audio_payload.data();
670 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700671 } else if (crypto_options_.sframe.require_frame_encryption) {
672 RTC_DLOG(LS_ERROR)
673 << "FrameDecryptor required but not set, dropping packet";
674 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700675 }
676
Niels Möller530ead42018-10-04 14:28:39 +0200677 if (payload_data_length == 0) {
678 webrtc_rtp_header.frameType = kEmptyFrame;
679 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
680 }
681 return OnReceivedPayloadData(payload, payload_data_length,
682 &webrtc_rtp_header);
683}
684
Niels Möller349ade32018-11-16 09:50:42 +0100685// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100686// TODO(nisse): Drop always-true return value.
687bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200688 // Store playout timestamp for the received RTCP packet
689 UpdatePlayoutTimestamp(true);
690
691 // Deliver RTCP packet to RTP/RTCP module for parsing
692 _rtpRtcpModule->IncomingRtcpPacket(data, length);
693
694 int64_t rtt = GetRTT();
695 if (rtt == 0) {
696 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100697 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200698 }
699
700 int64_t nack_window_ms = rtt;
701 if (nack_window_ms < kMinRetransmissionWindowMs) {
702 nack_window_ms = kMinRetransmissionWindowMs;
703 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
704 nack_window_ms = kMaxRetransmissionWindowMs;
705 }
706
707 uint32_t ntp_secs = 0;
708 uint32_t ntp_frac = 0;
709 uint32_t rtp_timestamp = 0;
710 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
711 &rtp_timestamp)) {
712 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100713 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200714 }
715
716 {
717 rtc::CritScope lock(&ts_stats_lock_);
718 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
719 }
Niels Möller80c67622018-11-12 13:22:47 +0100720 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200721}
722
723int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100724 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200725 return _outputAudioLevel.LevelFullRange();
726}
727
728double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100729 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200730 return _outputAudioLevel.TotalEnergy();
731}
732
733double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100734 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200735 return _outputAudioLevel.TotalDuration();
736}
737
738void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100739 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200740 rtc::CritScope cs(&volume_settings_critsect_);
741 _outputGain = scaling;
742}
743
Niels Möller349ade32018-11-16 09:50:42 +0100744void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
745 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200746 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200747}
748
Niels Möller530ead42018-10-04 14:28:39 +0200749void ChannelReceive::RegisterReceiverCongestionControlObjects(
750 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100751 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200752 RTC_DCHECK(packet_router);
753 RTC_DCHECK(!packet_router_);
754 constexpr bool remb_candidate = false;
755 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
756 packet_router_ = packet_router;
757}
758
759void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100760 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200761 RTC_DCHECK(packet_router_);
762 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
763 packet_router_ = nullptr;
764}
765
Niels Möller349ade32018-11-16 09:50:42 +0100766CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
767 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200768 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100769 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200770
771 // The jitter statistics is updated for each received RTP packet and is
772 // based on received packets.
773 RtcpStatistics statistics;
774 StreamStatistician* statistician =
775 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
776 if (statistician) {
777 statistician->GetStatistics(&statistics,
778 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
779 }
780
781 stats.fractionLost = statistics.fraction_lost;
782 stats.cumulativeLost = statistics.packets_lost;
783 stats.extendedMax = statistics.extended_highest_sequence_number;
784 stats.jitterSamples = statistics.jitter;
785
786 // --- RTT
787 stats.rttMs = GetRTT();
788
789 // --- Data counters
790
791 size_t bytesReceived(0);
792 uint32_t packetsReceived(0);
793
794 if (statistician) {
795 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
796 }
797
798 stats.bytesReceived = bytesReceived;
799 stats.packetsReceived = packetsReceived;
800
801 // --- Timestamps
802 {
803 rtc::CritScope lock(&ts_stats_lock_);
804 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
805 }
Niels Möller80c67622018-11-12 13:22:47 +0100806 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200807}
808
Niels Möller349ade32018-11-16 09:50:42 +0100809void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
810 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200811 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100812 if (enable) {
813 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100814 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100815 } else {
816 rtp_receive_statistics_->SetMaxReorderingThreshold(
817 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200818 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100819 }
Niels Möller530ead42018-10-04 14:28:39 +0200820}
821
822// Called when we are missing one or more packets.
823int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
824 int length) {
825 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
826}
827
Niels Möllerdced9f62018-11-19 10:27:07 +0100828void ChannelReceive::SetAssociatedSendChannel(
829 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100830 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200831 rtc::CritScope lock(&assoc_send_channel_lock_);
832 associated_send_channel_ = channel;
833}
834
Niels Möller80c67622018-11-12 13:22:47 +0100835NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100836 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100837 NetworkStatistics stats;
838 int error = audio_coding_->GetNetworkStatistics(&stats);
839 RTC_DCHECK_EQ(0, error);
840 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200841}
842
Niels Möller80c67622018-11-12 13:22:47 +0100843AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100844 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100845 AudioDecodingCallStats stats;
846 audio_coding_->GetDecodingCallStatistics(&stats);
847 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200848}
849
850uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100851 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
852 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200853 rtc::CritScope lock(&video_sync_lock_);
854 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
855}
856
Niels Möller349ade32018-11-16 09:50:42 +0100857void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
858 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
859 // Limit to range accepted by both VoE and ACM, so we're at least getting as
860 // close as possible, instead of failing.
861 delay_ms = rtc::SafeClamp(delay_ms, 0, 10000);
862 if ((delay_ms < kVoiceEngineMinMinPlayoutDelayMs) ||
863 (delay_ms > kVoiceEngineMaxMinPlayoutDelayMs)) {
Niels Möller530ead42018-10-04 14:28:39 +0200864 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100865 return;
Niels Möller530ead42018-10-04 14:28:39 +0200866 }
Niels Möller349ade32018-11-16 09:50:42 +0100867 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200868 RTC_DLOG(LS_ERROR)
869 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200870 }
Niels Möller530ead42018-10-04 14:28:39 +0200871}
872
Niels Möller349ade32018-11-16 09:50:42 +0100873uint32_t ChannelReceive::GetPlayoutTimestamp() const {
874 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200875 {
876 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100877 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200878 }
Niels Möller530ead42018-10-04 14:28:39 +0200879}
880
881absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100882 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200883 Syncable::Info info;
884 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
885 &info.capture_time_ntp_frac, nullptr, nullptr,
886 &info.capture_time_source_clock) != 0) {
887 return absl::nullopt;
888 }
889 {
890 rtc::CritScope cs(&rtp_sources_lock_);
891 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
892 return absl::nullopt;
893 }
894 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
895 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
896 }
897 return info;
898}
899
900void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
901 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
902
903 if (!jitter_buffer_playout_timestamp_) {
904 // This can happen if this channel has not received any RTP packets. In
905 // this case, NetEq is not capable of computing a playout timestamp.
906 return;
907 }
908
909 uint16_t delay_ms = 0;
910 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
911 RTC_DLOG(LS_WARNING)
912 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
913 << " playout delay from the ADM";
914 return;
915 }
916
917 RTC_DCHECK(jitter_buffer_playout_timestamp_);
918 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
919
920 // Remove the playout delay.
921 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
922
923 {
924 rtc::CritScope lock(&video_sync_lock_);
925 if (!rtcp) {
926 playout_timestamp_rtp_ = playout_timestamp;
927 }
928 playout_delay_ms_ = delay_ms;
929 }
930}
931
932int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100933 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200934 // Default to the playout frequency if we've not gotten any packets yet.
935 // TODO(ossu): Zero clockrate can only happen if we've added an external
936 // decoder for a format we don't support internally. Remove once that way of
937 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100938 return (decoder && decoder->second.clockrate_hz != 0)
939 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200940 : audio_coding_->PlayoutFrequency();
941}
942
943int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800944 if (media_transport_) {
945 auto target_rate = media_transport_->GetLatestTargetTransferRate();
946 if (target_rate.has_value()) {
947 return target_rate->network_estimate.round_trip_time.ms();
948 }
949
950 return 0;
951 }
Niels Möller530ead42018-10-04 14:28:39 +0200952 RtcpMode method = _rtpRtcpModule->RTCP();
953 if (method == RtcpMode::kOff) {
954 return 0;
955 }
956 std::vector<RTCPReportBlock> report_blocks;
957 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
958
959 // TODO(nisse): Could we check the return value from the ->RTT() call below,
960 // instead of checking if we have any report blocks?
961 if (report_blocks.empty()) {
962 rtc::CritScope lock(&assoc_send_channel_lock_);
963 // Tries to get RTT from an associated channel.
964 if (!associated_send_channel_) {
965 return 0;
966 }
967 return associated_send_channel_->GetRTT();
968 }
969
970 int64_t rtt = 0;
971 int64_t avg_rtt = 0;
972 int64_t max_rtt = 0;
973 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100974 // TODO(nisse): This method computes RTT based on sender reports, even though
975 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200976 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
977 0) {
978 return 0;
979 }
980 return rtt;
981}
982
Niels Möller349ade32018-11-16 09:50:42 +0100983} // namespace
984
985std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
986 ProcessThread* module_process_thread,
987 AudioDeviceModule* audio_device_module,
988 MediaTransportInterface* media_transport,
989 Transport* rtcp_send_transport,
990 RtcEventLog* rtc_event_log,
991 uint32_t remote_ssrc,
992 size_t jitter_buffer_max_packets,
993 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100994 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100995 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100996 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
997 absl::optional<AudioCodecPairId> codec_pair_id,
998 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
999 const webrtc::CryptoOptions& crypto_options) {
1000 return absl::make_unique<ChannelReceive>(
1001 module_process_thread, audio_device_module, media_transport,
1002 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001003 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001004 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
1005 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +01001006}
1007
Niels Möller530ead42018-10-04 14:28:39 +02001008} // namespace voe
1009} // namespace webrtc