blob: b899dcf43fb950b2541048d1797d01e402232b8b [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öller7d76a312018-10-26 12:57:07 +020060webrtc::FrameType WebrtcFrameTypeForMediaTransportFrameType(
61 MediaTransportEncodedAudioFrame::FrameType frame_type) {
62 switch (frame_type) {
63 case MediaTransportEncodedAudioFrame::FrameType::kSpeech:
64 return kAudioFrameSpeech;
65 break;
66
67 case MediaTransportEncodedAudioFrame::FrameType::
68 kDiscountinuousTransmission:
69 return kAudioFrameCN;
70 break;
71 }
72}
73
74WebRtcRTPHeader CreateWebrtcRTPHeaderForMediaTransportFrame(
75 const MediaTransportEncodedAudioFrame& frame,
76 uint64_t channel_id) {
77 webrtc::WebRtcRTPHeader webrtc_header = {};
78 webrtc_header.header.payloadType = frame.payload_type();
79 webrtc_header.header.payload_type_frequency = frame.sampling_rate_hz();
80 webrtc_header.header.timestamp = frame.starting_sample_index();
81 webrtc_header.header.sequenceNumber = frame.sequence_number();
82
83 webrtc_header.frameType =
84 WebrtcFrameTypeForMediaTransportFrameType(frame.frame_type());
85
86 webrtc_header.header.ssrc = static_cast<uint32_t>(channel_id);
87
88 // The rest are initialized by the RTPHeader constructor.
89 return webrtc_header;
90}
91
Niels Möller349ade32018-11-16 09:50:42 +010092class ChannelReceive : public ChannelReceiveInterface,
93 public MediaTransportAudioSinkInterface {
94 public:
95 // Used for receive streams.
96 ChannelReceive(ProcessThread* module_process_thread,
97 AudioDeviceModule* audio_device_module,
98 MediaTransportInterface* media_transport,
99 Transport* rtcp_send_transport,
100 RtcEventLog* rtc_event_log,
101 uint32_t remote_ssrc,
102 size_t jitter_buffer_max_packets,
103 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100104 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100105 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100106 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
107 absl::optional<AudioCodecPairId> codec_pair_id,
108 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
109 const webrtc::CryptoOptions& crypto_options);
110 ~ChannelReceive() override;
111
112 void SetSink(AudioSinkInterface* sink) override;
113
114 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
115
116 // API methods
117
118 void StartPlayout() override;
119 void StopPlayout() override;
120
121 // Codecs
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100122 absl::optional<std::pair<int, SdpAudioFormat>>
123 GetReceiveCodec() const override;
Niels Möller349ade32018-11-16 09:50:42 +0100124
125 bool ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
126
127 // RtpPacketSinkInterface.
128 void OnRtpPacket(const RtpPacketReceived& packet) override;
129
130 // Muting, Volume and Level.
131 void SetChannelOutputVolumeScaling(float scaling) override;
132 int GetSpeechOutputLevelFullRange() const override;
133 // See description of "totalAudioEnergy" in the WebRTC stats spec:
134 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
135 double GetTotalOutputEnergy() const override;
136 double GetTotalOutputDuration() const override;
137
138 // Stats.
139 NetworkStatistics GetNetworkStatistics() const override;
140 AudioDecodingCallStats GetDecodingCallStatistics() const override;
141
142 // Audio+Video Sync.
143 uint32_t GetDelayEstimate() const override;
144 void SetMinimumPlayoutDelay(int delayMs) override;
145 uint32_t GetPlayoutTimestamp() const override;
146
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100147 // Audio quality.
148 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
149 int GetBaseMinimumPlayoutDelayMs() const override;
150
Niels Möller349ade32018-11-16 09:50:42 +0100151 // Produces the transport-related timestamps; current_delay_ms is left unset.
152 absl::optional<Syncable::Info> GetSyncInfo() const override;
153
154 // RTP+RTCP
155 void SetLocalSSRC(unsigned int ssrc) override;
156
157 void RegisterReceiverCongestionControlObjects(
158 PacketRouter* packet_router) override;
159 void ResetReceiverCongestionControlObjects() override;
160
161 CallReceiveStatistics GetRTCPStatistics() const override;
162 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
163
164 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
165 int sample_rate_hz,
166 AudioFrame* audio_frame) override;
167
168 int PreferredSampleRate() const override;
169
170 // Associate to a send channel.
171 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100172 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100173
174 std::vector<RtpSource> GetSources() const override;
175
176 private:
Niels Möller349ade32018-11-16 09:50:42 +0100177 bool ReceivePacket(const uint8_t* packet,
178 size_t packet_length,
179 const RTPHeader& header);
180 int ResendPackets(const uint16_t* sequence_numbers, int length);
181 void UpdatePlayoutTimestamp(bool rtcp);
182
183 int GetRtpTimestampRateHz() const;
184 int64_t GetRTT() const;
185
186 // MediaTransportAudioSinkInterface override;
187 void OnData(uint64_t channel_id,
188 MediaTransportEncodedAudioFrame frame) override;
189
190 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
191 size_t payloadSize,
192 const WebRtcRTPHeader* rtpHeader);
193
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100194 bool Playing() const {
195 rtc::CritScope lock(&playing_lock_);
196 return playing_;
197 }
198
Niels Möller349ade32018-11-16 09:50:42 +0100199 // Thread checkers document and lock usage of some methods to specific threads
200 // we know about. The goal is to eventually split up voe::ChannelReceive into
201 // parts with single-threaded semantics, and thereby reduce the need for
202 // locks.
203 rtc::ThreadChecker worker_thread_checker_;
204 rtc::ThreadChecker module_process_thread_checker_;
205 // Methods accessed from audio and video threads are checked for sequential-
206 // only access. We don't necessarily own and control these threads, so thread
207 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
208 // audio thread to another, but access is still sequential.
209 rtc::RaceChecker audio_thread_race_checker_;
210 rtc::RaceChecker video_capture_thread_race_checker_;
211 rtc::CriticalSection _callbackCritSect;
212 rtc::CriticalSection volume_settings_critsect_;
213
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100214 rtc::CriticalSection playing_lock_;
215 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100216
217 RtcEventLog* const event_log_;
218
219 // Indexed by payload type.
220 std::map<uint8_t, int> payload_type_frequencies_;
221
222 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
223 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
224 const uint32_t remote_ssrc_;
225
226 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
227 // queried on the worker thread.
228 rtc::CriticalSection rtp_sources_lock_;
229 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
230 absl::optional<uint32_t> last_received_rtp_timestamp_
231 RTC_GUARDED_BY(&rtp_sources_lock_);
232 absl::optional<int64_t> last_received_rtp_system_time_ms_
233 RTC_GUARDED_BY(&rtp_sources_lock_);
234 absl::optional<uint8_t> last_received_rtp_audio_level_
235 RTC_GUARDED_BY(&rtp_sources_lock_);
236
237 std::unique_ptr<AudioCodingModule> audio_coding_;
238 AudioSinkInterface* audio_sink_ = nullptr;
239 AudioLevel _outputAudioLevel;
240
241 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
242
243 // Timestamp of the audio pulled from NetEq.
244 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
245
246 rtc::CriticalSection video_sync_lock_;
247 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
248 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
249
250 rtc::CriticalSection ts_stats_lock_;
251
252 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
253 // The rtp timestamp of the first played out audio frame.
254 int64_t capture_start_rtp_time_stamp_;
255 // The capture ntp time (in local timebase) of the first played out audio
256 // frame.
257 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
258
259 // uses
260 ProcessThread* _moduleProcessThreadPtr;
261 AudioDeviceModule* _audioDeviceModulePtr;
262 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
263
264 // An associated send channel.
265 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100266 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100267 RTC_GUARDED_BY(assoc_send_channel_lock_);
268
269 PacketRouter* packet_router_ = nullptr;
270
271 rtc::ThreadChecker construction_thread_;
272
273 MediaTransportInterface* const media_transport_;
274
275 // E2EE Audio Frame Decryption
276 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
277 webrtc::CryptoOptions crypto_options_;
278};
Niels Möller530ead42018-10-04 14:28:39 +0200279
Niels Möller530ead42018-10-04 14:28:39 +0200280int32_t ChannelReceive::OnReceivedPayloadData(
281 const uint8_t* payloadData,
282 size_t payloadSize,
283 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200284 // We should not be receiving any RTP packets if media_transport is set.
285 RTC_CHECK(!media_transport_);
286
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100287 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200288 // Avoid inserting into NetEQ when we are not playing. Count the
289 // packet as discarded.
290 return 0;
291 }
292
293 // Push the incoming payload (parsed and ready for decoding) into the ACM
294 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
295 0) {
296 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
297 "push data to the ACM";
298 return -1;
299 }
300
301 int64_t round_trip_time = 0;
302 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
303
304 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
305 if (!nack_list.empty()) {
306 // Can't use nack_list.data() since it's not supported by all
307 // compilers.
308 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
309 }
310 return 0;
311}
312
Niels Möller7d76a312018-10-26 12:57:07 +0200313// MediaTransportAudioSinkInterface override.
314void ChannelReceive::OnData(uint64_t channel_id,
315 MediaTransportEncodedAudioFrame frame) {
316 RTC_CHECK(media_transport_);
317
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100318 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200319 // Avoid inserting into NetEQ when we are not playing. Count the
320 // packet as discarded.
321 return;
322 }
323
324 // Send encoded audio frame to Decoder / NetEq.
325 if (audio_coding_->IncomingPacket(
326 frame.encoded_data().data(), frame.encoded_data().size(),
327 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
328 0) {
329 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
330 "push data to the ACM";
331 }
332}
333
Niels Möller530ead42018-10-04 14:28:39 +0200334AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
335 int sample_rate_hz,
336 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100337 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200338 audio_frame->sample_rate_hz_ = sample_rate_hz;
339
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100340 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
341
Niels Möller530ead42018-10-04 14:28:39 +0200342 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
343 bool muted;
344 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
345 &muted) == -1) {
346 RTC_DLOG(LS_ERROR)
347 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
348 // In all likelihood, the audio in this frame is garbage. We return an
349 // error so that the audio mixer module doesn't add it to the mix. As
350 // a result, it won't be played out and the actions skipped here are
351 // irrelevant.
352 return AudioMixer::Source::AudioFrameInfo::kError;
353 }
354
355 if (muted) {
356 // TODO(henrik.lundin): We should be able to do better than this. But we
357 // will have to go through all the cases below where the audio samples may
358 // be used, and handle the muted case in some way.
359 AudioFrameOperations::Mute(audio_frame);
360 }
361
362 {
363 // Pass the audio buffers to an optional sink callback, before applying
364 // scaling/panning, as that applies to the mix operation.
365 // External recipients of the audio (e.g. via AudioTrack), will do their
366 // own mixing/dynamic processing.
367 rtc::CritScope cs(&_callbackCritSect);
368 if (audio_sink_) {
369 AudioSinkInterface::Data data(
370 audio_frame->data(), audio_frame->samples_per_channel_,
371 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
372 audio_frame->timestamp_);
373 audio_sink_->OnData(data);
374 }
375 }
376
377 float output_gain = 1.0f;
378 {
379 rtc::CritScope cs(&volume_settings_critsect_);
380 output_gain = _outputGain;
381 }
382
383 // Output volume scaling
384 if (output_gain < 0.99f || output_gain > 1.01f) {
385 // TODO(solenberg): Combine with mute state - this can cause clicks!
386 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
387 }
388
389 // Measure audio level (0-9)
390 // TODO(henrik.lundin) Use the |muted| information here too.
391 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
392 // https://crbug.com/webrtc/7517).
393 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
394
395 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
396 // The first frame with a valid rtp timestamp.
397 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
398 }
399
400 if (capture_start_rtp_time_stamp_ >= 0) {
401 // audio_frame.timestamp_ should be valid from now on.
402
403 // Compute elapsed time.
404 int64_t unwrap_timestamp =
405 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
406 audio_frame->elapsed_time_ms_ =
407 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
408 (GetRtpTimestampRateHz() / 1000);
409
410 {
411 rtc::CritScope lock(&ts_stats_lock_);
412 // Compute ntp time.
413 audio_frame->ntp_time_ms_ =
414 ntp_estimator_.Estimate(audio_frame->timestamp_);
415 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
416 if (audio_frame->ntp_time_ms_ > 0) {
417 // Compute |capture_start_ntp_time_ms_| so that
418 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
419 capture_start_ntp_time_ms_ =
420 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
421 }
422 }
423 }
424
425 {
426 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
427 audio_coding_->TargetDelayMs());
428 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
429 rtc::CritScope lock(&video_sync_lock_);
430 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
431 jitter_buffer_delay + playout_delay_ms_);
432 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
433 jitter_buffer_delay);
434 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
435 playout_delay_ms_);
436 }
437
438 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
439 : AudioMixer::Source::AudioFrameInfo::kNormal;
440}
441
442int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100443 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200444 // Return the bigger of playout and receive frequency in the ACM.
445 return std::max(audio_coding_->ReceiveFrequency(),
446 audio_coding_->PlayoutFrequency());
447}
448
449ChannelReceive::ChannelReceive(
450 ProcessThread* module_process_thread,
451 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200452 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200453 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200454 RtcEventLog* rtc_event_log,
455 uint32_t remote_ssrc,
456 size_t jitter_buffer_max_packets,
457 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100458 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100459 bool jitter_buffer_enable_rtx_handling,
Niels Möller530ead42018-10-04 14:28:39 +0200460 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700461 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700462 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700463 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200464 : event_log_(rtc_event_log),
465 rtp_receive_statistics_(
466 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
467 remote_ssrc_(remote_ssrc),
468 _outputAudioLevel(),
469 ntp_estimator_(Clock::GetRealTimeClock()),
470 playout_timestamp_rtp_(0),
471 playout_delay_ms_(0),
472 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
473 capture_start_rtp_time_stamp_(-1),
474 capture_start_ntp_time_ms_(-1),
475 _moduleProcessThreadPtr(module_process_thread),
476 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200477 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700478 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200479 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700480 frame_decryptor_(frame_decryptor),
481 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100482 // TODO(nisse): Use _moduleProcessThreadPtr instead?
483 module_process_thread_checker_.DetachFromThread();
484
Niels Möller530ead42018-10-04 14:28:39 +0200485 RTC_DCHECK(module_process_thread);
486 RTC_DCHECK(audio_device_module);
487 AudioCodingModule::Config acm_config;
488 acm_config.decoder_factory = decoder_factory;
489 acm_config.neteq_config.codec_pair_id = codec_pair_id;
490 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
491 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100492 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200493 acm_config.neteq_config.enable_muted_state = true;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100494 acm_config.neteq_config.enable_rtx_handling =
495 jitter_buffer_enable_rtx_handling;
Niels Möller530ead42018-10-04 14:28:39 +0200496 audio_coding_.reset(AudioCodingModule::Create(acm_config));
497
498 _outputAudioLevel.Clear();
499
500 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
501 RtpRtcp::Configuration configuration;
502 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100503 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200504 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200505 configuration.receive_statistics = rtp_receive_statistics_.get();
506
507 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200508
509 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
510 _rtpRtcpModule->SetSendingMediaStatus(false);
511 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200512
Niels Möller530ead42018-10-04 14:28:39 +0200513 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
514
Niels Möller530ead42018-10-04 14:28:39 +0200515 // Ensure that RTCP is enabled by default for the created channel.
516 // Note that, the module will keep generating RTCP until it is explicitly
517 // disabled by the user.
518 // After StopListen (when no sockets exists), RTCP packets will no longer
519 // be transmitted since the Transport object will then be invalid.
520 // RTCP is enabled by default.
521 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200522
523 if (media_transport_) {
524 media_transport_->SetReceiveAudioSink(this);
525 }
Niels Möller530ead42018-10-04 14:28:39 +0200526}
527
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100528ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200529 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200530
531 if (media_transport_) {
532 media_transport_->SetReceiveAudioSink(nullptr);
533 }
534
Niels Möller530ead42018-10-04 14:28:39 +0200535 StopPlayout();
536
Niels Möller530ead42018-10-04 14:28:39 +0200537 int error = audio_coding_->RegisterTransportCallback(NULL);
538 RTC_DCHECK_EQ(0, error);
539
Niels Möller530ead42018-10-04 14:28:39 +0200540 if (_moduleProcessThreadPtr)
541 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200542}
543
544void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100545 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200546 rtc::CritScope cs(&_callbackCritSect);
547 audio_sink_ = sink;
548}
549
Niels Möller80c67622018-11-12 13:22:47 +0100550void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100551 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100552 rtc::CritScope lock(&playing_lock_);
553 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200554}
555
Niels Möller80c67622018-11-12 13:22:47 +0100556void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100557 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100558 rtc::CritScope lock(&playing_lock_);
559 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200560 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200561}
562
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100563absl::optional<std::pair<int, SdpAudioFormat>>
564 ChannelReceive::GetReceiveCodec() const {
Niels Möller349ade32018-11-16 09:50:42 +0100565 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100566 return audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200567}
568
569std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100570 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200571 int64_t now_ms = rtc::TimeMillis();
572 std::vector<RtpSource> sources;
573 {
574 rtc::CritScope cs(&rtp_sources_lock_);
575 sources = contributing_sources_.GetSources(now_ms);
576 if (last_received_rtp_system_time_ms_ >=
577 now_ms - ContributingSources::kHistoryMs) {
578 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
579 RtpSourceType::SSRC);
580 sources.back().set_audio_level(last_received_rtp_audio_level_);
581 }
582 }
583 return sources;
584}
585
586void ChannelReceive::SetReceiveCodecs(
587 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100588 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200589 for (const auto& kv : codecs) {
590 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
591 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
592 }
593 audio_coding_->SetReceiveCodecs(codecs);
594}
595
Niels Möller349ade32018-11-16 09:50:42 +0100596// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200597void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
598 int64_t now_ms = rtc::TimeMillis();
599 uint8_t audio_level;
600 bool voice_activity;
601 bool has_audio_level =
602 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
603
604 {
605 rtc::CritScope cs(&rtp_sources_lock_);
606 last_received_rtp_timestamp_ = packet.Timestamp();
607 last_received_rtp_system_time_ms_ = now_ms;
608 if (has_audio_level)
609 last_received_rtp_audio_level_ = audio_level;
610 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100611 contributing_sources_.Update(
612 now_ms, csrcs,
613 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200614 }
615
616 // Store playout timestamp for the received RTP packet
617 UpdatePlayoutTimestamp(false);
618
619 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
620 if (it == payload_type_frequencies_.end())
621 return;
622 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
623 RtpPacketReceived packet_copy(packet);
624 packet_copy.set_payload_type_frequency(it->second);
625
626 rtp_receive_statistics_->OnRtpPacket(packet_copy);
627
628 RTPHeader header;
629 packet_copy.GetHeader(&header);
630
631 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
632}
633
634bool ChannelReceive::ReceivePacket(const uint8_t* packet,
635 size_t packet_length,
636 const RTPHeader& header) {
637 const uint8_t* payload = packet + header.headerLength;
638 assert(packet_length >= header.headerLength);
639 size_t payload_length = packet_length - header.headerLength;
640 WebRtcRTPHeader webrtc_rtp_header = {};
641 webrtc_rtp_header.header = header;
642
Benjamin Wright84583f62018-10-04 14:22:34 -0700643 size_t payload_data_length = payload_length - header.paddingLength;
644
645 // E2EE Custom Audio Frame Decryption (This is optional).
646 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
647 rtc::Buffer decrypted_audio_payload;
648 if (frame_decryptor_ != nullptr) {
649 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
650 cricket::MEDIA_TYPE_AUDIO, payload_length);
651 decrypted_audio_payload.SetSize(max_plaintext_size);
652
653 size_t bytes_written = 0;
654 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
655 header.arrOfCSRCs + header.numCSRCs);
656 int decrypt_status = frame_decryptor_->Decrypt(
657 cricket::MEDIA_TYPE_AUDIO, csrcs,
658 /*additional_data=*/nullptr,
659 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
660 decrypted_audio_payload, &bytes_written);
661
662 // In this case just interpret the failure as a silent frame.
663 if (decrypt_status != 0) {
664 bytes_written = 0;
665 }
666
667 // Resize the decrypted audio payload to the number of bytes actually
668 // written.
669 decrypted_audio_payload.SetSize(bytes_written);
670 // Update the final payload.
671 payload = decrypted_audio_payload.data();
672 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700673 } else if (crypto_options_.sframe.require_frame_encryption) {
674 RTC_DLOG(LS_ERROR)
675 << "FrameDecryptor required but not set, dropping packet";
676 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700677 }
678
Niels Möller530ead42018-10-04 14:28:39 +0200679 if (payload_data_length == 0) {
680 webrtc_rtp_header.frameType = kEmptyFrame;
681 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
682 }
683 return OnReceivedPayloadData(payload, payload_data_length,
684 &webrtc_rtp_header);
685}
686
Niels Möller349ade32018-11-16 09:50:42 +0100687// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100688// TODO(nisse): Drop always-true return value.
689bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200690 // Store playout timestamp for the received RTCP packet
691 UpdatePlayoutTimestamp(true);
692
693 // Deliver RTCP packet to RTP/RTCP module for parsing
694 _rtpRtcpModule->IncomingRtcpPacket(data, length);
695
696 int64_t rtt = GetRTT();
697 if (rtt == 0) {
698 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100699 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200700 }
701
Niels Möller530ead42018-10-04 14:28:39 +0200702 uint32_t ntp_secs = 0;
703 uint32_t ntp_frac = 0;
704 uint32_t rtp_timestamp = 0;
705 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
706 &rtp_timestamp)) {
707 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100708 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200709 }
710
711 {
712 rtc::CritScope lock(&ts_stats_lock_);
713 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
714 }
Niels Möller80c67622018-11-12 13:22:47 +0100715 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200716}
717
718int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100719 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200720 return _outputAudioLevel.LevelFullRange();
721}
722
723double ChannelReceive::GetTotalOutputEnergy() 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.TotalEnergy();
726}
727
728double ChannelReceive::GetTotalOutputDuration() 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.TotalDuration();
731}
732
733void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100734 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200735 rtc::CritScope cs(&volume_settings_critsect_);
736 _outputGain = scaling;
737}
738
Niels Möller349ade32018-11-16 09:50:42 +0100739void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
740 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200741 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200742}
743
Niels Möller530ead42018-10-04 14:28:39 +0200744void ChannelReceive::RegisterReceiverCongestionControlObjects(
745 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100746 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200747 RTC_DCHECK(packet_router);
748 RTC_DCHECK(!packet_router_);
749 constexpr bool remb_candidate = false;
750 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
751 packet_router_ = packet_router;
752}
753
754void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100755 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200756 RTC_DCHECK(packet_router_);
757 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
758 packet_router_ = nullptr;
759}
760
Niels Möller349ade32018-11-16 09:50:42 +0100761CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
762 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200763 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100764 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200765
766 // The jitter statistics is updated for each received RTP packet and is
767 // based on received packets.
768 RtcpStatistics statistics;
769 StreamStatistician* statistician =
770 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
771 if (statistician) {
772 statistician->GetStatistics(&statistics,
773 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
774 }
775
776 stats.fractionLost = statistics.fraction_lost;
777 stats.cumulativeLost = statistics.packets_lost;
778 stats.extendedMax = statistics.extended_highest_sequence_number;
779 stats.jitterSamples = statistics.jitter;
780
781 // --- RTT
782 stats.rttMs = GetRTT();
783
784 // --- Data counters
785
786 size_t bytesReceived(0);
787 uint32_t packetsReceived(0);
788
789 if (statistician) {
790 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
791 }
792
793 stats.bytesReceived = bytesReceived;
794 stats.packetsReceived = packetsReceived;
795
796 // --- Timestamps
797 {
798 rtc::CritScope lock(&ts_stats_lock_);
799 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
800 }
Niels Möller80c67622018-11-12 13:22:47 +0100801 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200802}
803
Niels Möller349ade32018-11-16 09:50:42 +0100804void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
805 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200806 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100807 if (enable) {
808 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100809 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100810 } else {
811 rtp_receive_statistics_->SetMaxReorderingThreshold(
812 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200813 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100814 }
Niels Möller530ead42018-10-04 14:28:39 +0200815}
816
817// Called when we are missing one or more packets.
818int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
819 int length) {
820 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
821}
822
Niels Möllerdced9f62018-11-19 10:27:07 +0100823void ChannelReceive::SetAssociatedSendChannel(
824 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100825 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200826 rtc::CritScope lock(&assoc_send_channel_lock_);
827 associated_send_channel_ = channel;
828}
829
Niels Möller80c67622018-11-12 13:22:47 +0100830NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100831 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100832 NetworkStatistics stats;
833 int error = audio_coding_->GetNetworkStatistics(&stats);
834 RTC_DCHECK_EQ(0, error);
835 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200836}
837
Niels Möller80c67622018-11-12 13:22:47 +0100838AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100839 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100840 AudioDecodingCallStats stats;
841 audio_coding_->GetDecodingCallStatistics(&stats);
842 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200843}
844
845uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100846 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
847 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200848 rtc::CritScope lock(&video_sync_lock_);
849 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
850}
851
Niels Möller349ade32018-11-16 09:50:42 +0100852void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
853 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
854 // Limit to range accepted by both VoE and ACM, so we're at least getting as
855 // close as possible, instead of failing.
Ruslan Burakov432c8332019-02-03 22:21:02 +0100856 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
857 kVoiceEngineMaxMinPlayoutDelayMs);
Niels Möller349ade32018-11-16 09:50:42 +0100858 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200859 RTC_DLOG(LS_ERROR)
860 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200861 }
Niels Möller530ead42018-10-04 14:28:39 +0200862}
863
Niels Möller349ade32018-11-16 09:50:42 +0100864uint32_t ChannelReceive::GetPlayoutTimestamp() const {
865 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200866 {
867 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100868 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200869 }
Niels Möller530ead42018-10-04 14:28:39 +0200870}
871
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100872bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
873 return audio_coding_->SetBaseMinimumPlayoutDelayMs(delay_ms);
874}
875
876int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
877 return audio_coding_->GetBaseMinimumPlayoutDelayMs();
878}
879
Niels Möller530ead42018-10-04 14:28:39 +0200880absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100881 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200882 Syncable::Info info;
883 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
884 &info.capture_time_ntp_frac, nullptr, nullptr,
885 &info.capture_time_source_clock) != 0) {
886 return absl::nullopt;
887 }
888 {
889 rtc::CritScope cs(&rtp_sources_lock_);
890 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
891 return absl::nullopt;
892 }
893 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
894 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
895 }
896 return info;
897}
898
899void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
900 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
901
902 if (!jitter_buffer_playout_timestamp_) {
903 // This can happen if this channel has not received any RTP packets. In
904 // this case, NetEq is not capable of computing a playout timestamp.
905 return;
906 }
907
908 uint16_t delay_ms = 0;
909 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
910 RTC_DLOG(LS_WARNING)
911 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
912 << " playout delay from the ADM";
913 return;
914 }
915
916 RTC_DCHECK(jitter_buffer_playout_timestamp_);
917 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
918
919 // Remove the playout delay.
920 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
921
922 {
923 rtc::CritScope lock(&video_sync_lock_);
924 if (!rtcp) {
925 playout_timestamp_rtp_ = playout_timestamp;
926 }
927 playout_delay_ms_ = delay_ms;
928 }
929}
930
931int ChannelReceive::GetRtpTimestampRateHz() const {
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100932 const auto decoder = audio_coding_->ReceiveCodec();
Niels Möller530ead42018-10-04 14:28:39 +0200933 // Default to the playout frequency if we've not gotten any packets yet.
934 // TODO(ossu): Zero clockrate can only happen if we've added an external
935 // decoder for a format we don't support internally. Remove once that way of
936 // adding decoders is gone!
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100937 return (decoder && decoder->second.clockrate_hz != 0)
938 ? decoder->second.clockrate_hz
Niels Möller530ead42018-10-04 14:28:39 +0200939 : audio_coding_->PlayoutFrequency();
940}
941
942int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800943 if (media_transport_) {
944 auto target_rate = media_transport_->GetLatestTargetTransferRate();
945 if (target_rate.has_value()) {
946 return target_rate->network_estimate.round_trip_time.ms();
947 }
948
949 return 0;
950 }
Niels Möller530ead42018-10-04 14:28:39 +0200951 RtcpMode method = _rtpRtcpModule->RTCP();
952 if (method == RtcpMode::kOff) {
953 return 0;
954 }
955 std::vector<RTCPReportBlock> report_blocks;
956 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
957
958 // TODO(nisse): Could we check the return value from the ->RTT() call below,
959 // instead of checking if we have any report blocks?
960 if (report_blocks.empty()) {
961 rtc::CritScope lock(&assoc_send_channel_lock_);
962 // Tries to get RTT from an associated channel.
963 if (!associated_send_channel_) {
964 return 0;
965 }
966 return associated_send_channel_->GetRTT();
967 }
968
969 int64_t rtt = 0;
970 int64_t avg_rtt = 0;
971 int64_t max_rtt = 0;
972 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100973 // TODO(nisse): This method computes RTT based on sender reports, even though
974 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200975 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
976 0) {
977 return 0;
978 }
979 return rtt;
980}
981
Niels Möller349ade32018-11-16 09:50:42 +0100982} // namespace
983
984std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
985 ProcessThread* module_process_thread,
986 AudioDeviceModule* audio_device_module,
987 MediaTransportInterface* media_transport,
988 Transport* rtcp_send_transport,
989 RtcEventLog* rtc_event_log,
990 uint32_t remote_ssrc,
991 size_t jitter_buffer_max_packets,
992 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100993 int jitter_buffer_min_delay_ms,
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100994 bool jitter_buffer_enable_rtx_handling,
Niels Möller349ade32018-11-16 09:50:42 +0100995 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
996 absl::optional<AudioCodecPairId> codec_pair_id,
997 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
998 const webrtc::CryptoOptions& crypto_options) {
999 return absl::make_unique<ChannelReceive>(
1000 module_process_thread, audio_device_module, media_transport,
1001 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001002 jitter_buffer_max_packets, jitter_buffer_fast_playout,
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001003 jitter_buffer_min_delay_ms, jitter_buffer_enable_rtx_handling,
1004 decoder_factory, codec_pair_id, frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +01001005}
1006
Niels Möller530ead42018-10-04 14:28:39 +02001007} // namespace voe
1008} // namespace webrtc