blob: f2d7c9d662cd1359a57203d55e3f5837df0cbd79 [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"
39#include "rtc_base/criticalsection.h"
40#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"
46#include "rtc_base/timeutils.h"
47#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,
Niels Möller349ade32018-11-16 09:50:42 +0100107 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
108 absl::optional<AudioCodecPairId> codec_pair_id,
109 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
110 const webrtc::CryptoOptions& crypto_options);
111 ~ChannelReceive() override;
112
113 void SetSink(AudioSinkInterface* sink) override;
114
115 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
116
117 // API methods
118
119 void StartPlayout() override;
120 void StopPlayout() override;
121
122 // Codecs
123 bool GetRecCodec(CodecInst* codec) const override;
124
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
147 // Produces the transport-related timestamps; current_delay_ms is left unset.
148 absl::optional<Syncable::Info> GetSyncInfo() const override;
149
150 // RTP+RTCP
151 void SetLocalSSRC(unsigned int ssrc) override;
152
153 void RegisterReceiverCongestionControlObjects(
154 PacketRouter* packet_router) override;
155 void ResetReceiverCongestionControlObjects() override;
156
157 CallReceiveStatistics GetRTCPStatistics() const override;
158 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
159
160 AudioMixer::Source::AudioFrameInfo GetAudioFrameWithInfo(
161 int sample_rate_hz,
162 AudioFrame* audio_frame) override;
163
164 int PreferredSampleRate() const override;
165
166 // Associate to a send channel.
167 // Used for obtaining RTT for a receive-only channel.
Niels Möllerdced9f62018-11-19 10:27:07 +0100168 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
Niels Möller349ade32018-11-16 09:50:42 +0100169
170 std::vector<RtpSource> GetSources() const override;
171
172 private:
Niels Möller349ade32018-11-16 09:50:42 +0100173 bool ReceivePacket(const uint8_t* packet,
174 size_t packet_length,
175 const RTPHeader& header);
176 int ResendPackets(const uint16_t* sequence_numbers, int length);
177 void UpdatePlayoutTimestamp(bool rtcp);
178
179 int GetRtpTimestampRateHz() const;
180 int64_t GetRTT() const;
181
182 // MediaTransportAudioSinkInterface override;
183 void OnData(uint64_t channel_id,
184 MediaTransportEncodedAudioFrame frame) override;
185
186 int32_t OnReceivedPayloadData(const uint8_t* payloadData,
187 size_t payloadSize,
188 const WebRtcRTPHeader* rtpHeader);
189
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100190 bool Playing() const {
191 rtc::CritScope lock(&playing_lock_);
192 return playing_;
193 }
194
Niels Möller349ade32018-11-16 09:50:42 +0100195 // Thread checkers document and lock usage of some methods to specific threads
196 // we know about. The goal is to eventually split up voe::ChannelReceive into
197 // parts with single-threaded semantics, and thereby reduce the need for
198 // locks.
199 rtc::ThreadChecker worker_thread_checker_;
200 rtc::ThreadChecker module_process_thread_checker_;
201 // Methods accessed from audio and video threads are checked for sequential-
202 // only access. We don't necessarily own and control these threads, so thread
203 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
204 // audio thread to another, but access is still sequential.
205 rtc::RaceChecker audio_thread_race_checker_;
206 rtc::RaceChecker video_capture_thread_race_checker_;
207 rtc::CriticalSection _callbackCritSect;
208 rtc::CriticalSection volume_settings_critsect_;
209
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100210 rtc::CriticalSection playing_lock_;
211 bool playing_ RTC_GUARDED_BY(&playing_lock_) = false;
Niels Möller349ade32018-11-16 09:50:42 +0100212
213 RtcEventLog* const event_log_;
214
215 // Indexed by payload type.
216 std::map<uint8_t, int> payload_type_frequencies_;
217
218 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
219 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
220 const uint32_t remote_ssrc_;
221
222 // Info for GetSources and GetSyncInfo is updated on network or worker thread,
223 // queried on the worker thread.
224 rtc::CriticalSection rtp_sources_lock_;
225 ContributingSources contributing_sources_ RTC_GUARDED_BY(&rtp_sources_lock_);
226 absl::optional<uint32_t> last_received_rtp_timestamp_
227 RTC_GUARDED_BY(&rtp_sources_lock_);
228 absl::optional<int64_t> last_received_rtp_system_time_ms_
229 RTC_GUARDED_BY(&rtp_sources_lock_);
230 absl::optional<uint8_t> last_received_rtp_audio_level_
231 RTC_GUARDED_BY(&rtp_sources_lock_);
232
233 std::unique_ptr<AudioCodingModule> audio_coding_;
234 AudioSinkInterface* audio_sink_ = nullptr;
235 AudioLevel _outputAudioLevel;
236
237 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
238
239 // Timestamp of the audio pulled from NetEq.
240 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
241
242 rtc::CriticalSection video_sync_lock_;
243 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(video_sync_lock_);
244 uint32_t playout_delay_ms_ RTC_GUARDED_BY(video_sync_lock_);
245
246 rtc::CriticalSection ts_stats_lock_;
247
248 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
249 // The rtp timestamp of the first played out audio frame.
250 int64_t capture_start_rtp_time_stamp_;
251 // The capture ntp time (in local timebase) of the first played out audio
252 // frame.
253 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
254
255 // uses
256 ProcessThread* _moduleProcessThreadPtr;
257 AudioDeviceModule* _audioDeviceModulePtr;
258 float _outputGain RTC_GUARDED_BY(volume_settings_critsect_);
259
260 // An associated send channel.
261 rtc::CriticalSection assoc_send_channel_lock_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100262 const ChannelSendInterface* associated_send_channel_
Niels Möller349ade32018-11-16 09:50:42 +0100263 RTC_GUARDED_BY(assoc_send_channel_lock_);
264
265 PacketRouter* packet_router_ = nullptr;
266
267 rtc::ThreadChecker construction_thread_;
268
269 MediaTransportInterface* const media_transport_;
270
271 // E2EE Audio Frame Decryption
272 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_;
273 webrtc::CryptoOptions crypto_options_;
274};
Niels Möller530ead42018-10-04 14:28:39 +0200275
Niels Möller530ead42018-10-04 14:28:39 +0200276int32_t ChannelReceive::OnReceivedPayloadData(
277 const uint8_t* payloadData,
278 size_t payloadSize,
279 const WebRtcRTPHeader* rtpHeader) {
Niels Möller7d76a312018-10-26 12:57:07 +0200280 // We should not be receiving any RTP packets if media_transport is set.
281 RTC_CHECK(!media_transport_);
282
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100283 if (!Playing()) {
Niels Möller530ead42018-10-04 14:28:39 +0200284 // Avoid inserting into NetEQ when we are not playing. Count the
285 // packet as discarded.
286 return 0;
287 }
288
289 // Push the incoming payload (parsed and ready for decoding) into the ACM
290 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
291 0) {
292 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
293 "push data to the ACM";
294 return -1;
295 }
296
297 int64_t round_trip_time = 0;
298 _rtpRtcpModule->RTT(remote_ssrc_, &round_trip_time, NULL, NULL, NULL);
299
300 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
301 if (!nack_list.empty()) {
302 // Can't use nack_list.data() since it's not supported by all
303 // compilers.
304 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
305 }
306 return 0;
307}
308
Niels Möller7d76a312018-10-26 12:57:07 +0200309// MediaTransportAudioSinkInterface override.
310void ChannelReceive::OnData(uint64_t channel_id,
311 MediaTransportEncodedAudioFrame frame) {
312 RTC_CHECK(media_transport_);
313
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100314 if (!Playing()) {
Niels Möller7d76a312018-10-26 12:57:07 +0200315 // Avoid inserting into NetEQ when we are not playing. Count the
316 // packet as discarded.
317 return;
318 }
319
320 // Send encoded audio frame to Decoder / NetEq.
321 if (audio_coding_->IncomingPacket(
322 frame.encoded_data().data(), frame.encoded_data().size(),
323 CreateWebrtcRTPHeaderForMediaTransportFrame(frame, channel_id)) !=
324 0) {
325 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnData: unable to "
326 "push data to the ACM";
327 }
328}
329
Niels Möller530ead42018-10-04 14:28:39 +0200330AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
331 int sample_rate_hz,
332 AudioFrame* audio_frame) {
Niels Möller349ade32018-11-16 09:50:42 +0100333 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200334 audio_frame->sample_rate_hz_ = sample_rate_hz;
335
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100336 event_log_->Log(absl::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
337
Niels Möller530ead42018-10-04 14:28:39 +0200338 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
339 bool muted;
340 if (audio_coding_->PlayoutData10Ms(audio_frame->sample_rate_hz_, audio_frame,
341 &muted) == -1) {
342 RTC_DLOG(LS_ERROR)
343 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
344 // In all likelihood, the audio in this frame is garbage. We return an
345 // error so that the audio mixer module doesn't add it to the mix. As
346 // a result, it won't be played out and the actions skipped here are
347 // irrelevant.
348 return AudioMixer::Source::AudioFrameInfo::kError;
349 }
350
351 if (muted) {
352 // TODO(henrik.lundin): We should be able to do better than this. But we
353 // will have to go through all the cases below where the audio samples may
354 // be used, and handle the muted case in some way.
355 AudioFrameOperations::Mute(audio_frame);
356 }
357
358 {
359 // Pass the audio buffers to an optional sink callback, before applying
360 // scaling/panning, as that applies to the mix operation.
361 // External recipients of the audio (e.g. via AudioTrack), will do their
362 // own mixing/dynamic processing.
363 rtc::CritScope cs(&_callbackCritSect);
364 if (audio_sink_) {
365 AudioSinkInterface::Data data(
366 audio_frame->data(), audio_frame->samples_per_channel_,
367 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
368 audio_frame->timestamp_);
369 audio_sink_->OnData(data);
370 }
371 }
372
373 float output_gain = 1.0f;
374 {
375 rtc::CritScope cs(&volume_settings_critsect_);
376 output_gain = _outputGain;
377 }
378
379 // Output volume scaling
380 if (output_gain < 0.99f || output_gain > 1.01f) {
381 // TODO(solenberg): Combine with mute state - this can cause clicks!
382 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
383 }
384
385 // Measure audio level (0-9)
386 // TODO(henrik.lundin) Use the |muted| information here too.
387 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| (see
388 // https://crbug.com/webrtc/7517).
389 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
390
391 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
392 // The first frame with a valid rtp timestamp.
393 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
394 }
395
396 if (capture_start_rtp_time_stamp_ >= 0) {
397 // audio_frame.timestamp_ should be valid from now on.
398
399 // Compute elapsed time.
400 int64_t unwrap_timestamp =
401 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
402 audio_frame->elapsed_time_ms_ =
403 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
404 (GetRtpTimestampRateHz() / 1000);
405
406 {
407 rtc::CritScope lock(&ts_stats_lock_);
408 // Compute ntp time.
409 audio_frame->ntp_time_ms_ =
410 ntp_estimator_.Estimate(audio_frame->timestamp_);
411 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
412 if (audio_frame->ntp_time_ms_ > 0) {
413 // Compute |capture_start_ntp_time_ms_| so that
414 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
415 capture_start_ntp_time_ms_ =
416 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
417 }
418 }
419 }
420
421 {
422 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
423 audio_coding_->TargetDelayMs());
424 const int jitter_buffer_delay = audio_coding_->FilteredCurrentDelayMs();
425 rtc::CritScope lock(&video_sync_lock_);
426 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
427 jitter_buffer_delay + playout_delay_ms_);
428 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
429 jitter_buffer_delay);
430 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
431 playout_delay_ms_);
432 }
433
434 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
435 : AudioMixer::Source::AudioFrameInfo::kNormal;
436}
437
438int ChannelReceive::PreferredSampleRate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100439 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200440 // Return the bigger of playout and receive frequency in the ACM.
441 return std::max(audio_coding_->ReceiveFrequency(),
442 audio_coding_->PlayoutFrequency());
443}
444
445ChannelReceive::ChannelReceive(
446 ProcessThread* module_process_thread,
447 AudioDeviceModule* audio_device_module,
Niels Möller7d76a312018-10-26 12:57:07 +0200448 MediaTransportInterface* media_transport,
Niels Möllerae4237e2018-10-05 11:28:38 +0200449 Transport* rtcp_send_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200450 RtcEventLog* rtc_event_log,
451 uint32_t remote_ssrc,
452 size_t jitter_buffer_max_packets,
453 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100454 int jitter_buffer_min_delay_ms,
Niels Möller530ead42018-10-04 14:28:39 +0200455 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
Benjamin Wright84583f62018-10-04 14:22:34 -0700456 absl::optional<AudioCodecPairId> codec_pair_id,
Benjamin Wright78410ad2018-10-25 09:52:57 -0700457 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700458 const webrtc::CryptoOptions& crypto_options)
Niels Möller530ead42018-10-04 14:28:39 +0200459 : event_log_(rtc_event_log),
460 rtp_receive_statistics_(
461 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
462 remote_ssrc_(remote_ssrc),
463 _outputAudioLevel(),
464 ntp_estimator_(Clock::GetRealTimeClock()),
465 playout_timestamp_rtp_(0),
466 playout_delay_ms_(0),
467 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
468 capture_start_rtp_time_stamp_(-1),
469 capture_start_ntp_time_ms_(-1),
470 _moduleProcessThreadPtr(module_process_thread),
471 _audioDeviceModulePtr(audio_device_module),
Niels Möller530ead42018-10-04 14:28:39 +0200472 _outputGain(1.0f),
Benjamin Wright84583f62018-10-04 14:22:34 -0700473 associated_send_channel_(nullptr),
Niels Möller7d76a312018-10-26 12:57:07 +0200474 media_transport_(media_transport),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700475 frame_decryptor_(frame_decryptor),
476 crypto_options_(crypto_options) {
Niels Möller349ade32018-11-16 09:50:42 +0100477 // TODO(nisse): Use _moduleProcessThreadPtr instead?
478 module_process_thread_checker_.DetachFromThread();
479
Niels Möller530ead42018-10-04 14:28:39 +0200480 RTC_DCHECK(module_process_thread);
481 RTC_DCHECK(audio_device_module);
482 AudioCodingModule::Config acm_config;
483 acm_config.decoder_factory = decoder_factory;
484 acm_config.neteq_config.codec_pair_id = codec_pair_id;
485 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
486 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100487 acm_config.neteq_config.min_delay_ms = jitter_buffer_min_delay_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200488 acm_config.neteq_config.enable_muted_state = true;
489 audio_coding_.reset(AudioCodingModule::Create(acm_config));
490
491 _outputAudioLevel.Clear();
492
493 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
494 RtpRtcp::Configuration configuration;
495 configuration.audio = true;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100496 configuration.receiver_only = true;
Niels Möllerae4237e2018-10-05 11:28:38 +0200497 configuration.outgoing_transport = rtcp_send_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200498 configuration.receive_statistics = rtp_receive_statistics_.get();
499
500 configuration.event_log = event_log_;
Niels Möller530ead42018-10-04 14:28:39 +0200501
502 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
503 _rtpRtcpModule->SetSendingMediaStatus(false);
504 _rtpRtcpModule->SetRemoteSSRC(remote_ssrc_);
Niels Möller530ead42018-10-04 14:28:39 +0200505
Niels Möller530ead42018-10-04 14:28:39 +0200506 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
507
Niels Möller530ead42018-10-04 14:28:39 +0200508 // Ensure that RTCP is enabled by default for the created channel.
509 // Note that, the module will keep generating RTCP until it is explicitly
510 // disabled by the user.
511 // After StopListen (when no sockets exists), RTCP packets will no longer
512 // be transmitted since the Transport object will then be invalid.
513 // RTCP is enabled by default.
514 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
Niels Möller7d76a312018-10-26 12:57:07 +0200515
516 if (media_transport_) {
517 media_transport_->SetReceiveAudioSink(this);
518 }
Niels Möller530ead42018-10-04 14:28:39 +0200519}
520
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100521ChannelReceive::~ChannelReceive() {
Niels Möller530ead42018-10-04 14:28:39 +0200522 RTC_DCHECK(construction_thread_.CalledOnValidThread());
Niels Möller7d76a312018-10-26 12:57:07 +0200523
524 if (media_transport_) {
525 media_transport_->SetReceiveAudioSink(nullptr);
526 }
527
Niels Möller530ead42018-10-04 14:28:39 +0200528 StopPlayout();
529
Niels Möller530ead42018-10-04 14:28:39 +0200530 int error = audio_coding_->RegisterTransportCallback(NULL);
531 RTC_DCHECK_EQ(0, error);
532
Niels Möller530ead42018-10-04 14:28:39 +0200533 if (_moduleProcessThreadPtr)
534 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200535}
536
537void ChannelReceive::SetSink(AudioSinkInterface* sink) {
Niels Möller349ade32018-11-16 09:50:42 +0100538 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200539 rtc::CritScope cs(&_callbackCritSect);
540 audio_sink_ = sink;
541}
542
Niels Möller80c67622018-11-12 13:22:47 +0100543void ChannelReceive::StartPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100544 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100545 rtc::CritScope lock(&playing_lock_);
546 playing_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200547}
548
Niels Möller80c67622018-11-12 13:22:47 +0100549void ChannelReceive::StopPlayout() {
Niels Möller349ade32018-11-16 09:50:42 +0100550 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Fredrik Solenbergc5e8be32018-11-19 11:56:13 +0100551 rtc::CritScope lock(&playing_lock_);
552 playing_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200553 _outputAudioLevel.Clear();
Niels Möller530ead42018-10-04 14:28:39 +0200554}
555
Niels Möller349ade32018-11-16 09:50:42 +0100556bool ChannelReceive::GetRecCodec(CodecInst* codec) const {
557 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100558 return (audio_coding_->ReceiveCodec(codec) == 0);
Niels Möller530ead42018-10-04 14:28:39 +0200559}
560
561std::vector<webrtc::RtpSource> ChannelReceive::GetSources() const {
Niels Möller349ade32018-11-16 09:50:42 +0100562 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200563 int64_t now_ms = rtc::TimeMillis();
564 std::vector<RtpSource> sources;
565 {
566 rtc::CritScope cs(&rtp_sources_lock_);
567 sources = contributing_sources_.GetSources(now_ms);
568 if (last_received_rtp_system_time_ms_ >=
569 now_ms - ContributingSources::kHistoryMs) {
570 sources.emplace_back(*last_received_rtp_system_time_ms_, remote_ssrc_,
571 RtpSourceType::SSRC);
572 sources.back().set_audio_level(last_received_rtp_audio_level_);
573 }
574 }
575 return sources;
576}
577
578void ChannelReceive::SetReceiveCodecs(
579 const std::map<int, SdpAudioFormat>& codecs) {
Niels Möller349ade32018-11-16 09:50:42 +0100580 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200581 for (const auto& kv : codecs) {
582 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
583 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
584 }
585 audio_coding_->SetReceiveCodecs(codecs);
586}
587
Niels Möller349ade32018-11-16 09:50:42 +0100588// May be called on either worker thread or network thread.
Niels Möller530ead42018-10-04 14:28:39 +0200589void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
590 int64_t now_ms = rtc::TimeMillis();
591 uint8_t audio_level;
592 bool voice_activity;
593 bool has_audio_level =
594 packet.GetExtension<::webrtc::AudioLevel>(&voice_activity, &audio_level);
595
596 {
597 rtc::CritScope cs(&rtp_sources_lock_);
598 last_received_rtp_timestamp_ = packet.Timestamp();
599 last_received_rtp_system_time_ms_ = now_ms;
600 if (has_audio_level)
601 last_received_rtp_audio_level_ = audio_level;
602 std::vector<uint32_t> csrcs = packet.Csrcs();
Jonas Oreland967f7d52018-11-06 07:35:06 +0100603 contributing_sources_.Update(
604 now_ms, csrcs,
605 has_audio_level ? absl::optional<uint8_t>(audio_level) : absl::nullopt);
Niels Möller530ead42018-10-04 14:28:39 +0200606 }
607
608 // Store playout timestamp for the received RTP packet
609 UpdatePlayoutTimestamp(false);
610
611 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
612 if (it == payload_type_frequencies_.end())
613 return;
614 // TODO(nisse): Set payload_type_frequency earlier, when packet is parsed.
615 RtpPacketReceived packet_copy(packet);
616 packet_copy.set_payload_type_frequency(it->second);
617
618 rtp_receive_statistics_->OnRtpPacket(packet_copy);
619
620 RTPHeader header;
621 packet_copy.GetHeader(&header);
622
623 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
624}
625
626bool ChannelReceive::ReceivePacket(const uint8_t* packet,
627 size_t packet_length,
628 const RTPHeader& header) {
629 const uint8_t* payload = packet + header.headerLength;
630 assert(packet_length >= header.headerLength);
631 size_t payload_length = packet_length - header.headerLength;
632 WebRtcRTPHeader webrtc_rtp_header = {};
633 webrtc_rtp_header.header = header;
634
Benjamin Wright84583f62018-10-04 14:22:34 -0700635 size_t payload_data_length = payload_length - header.paddingLength;
636
637 // E2EE Custom Audio Frame Decryption (This is optional).
638 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
639 rtc::Buffer decrypted_audio_payload;
640 if (frame_decryptor_ != nullptr) {
641 size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
642 cricket::MEDIA_TYPE_AUDIO, payload_length);
643 decrypted_audio_payload.SetSize(max_plaintext_size);
644
645 size_t bytes_written = 0;
646 std::vector<uint32_t> csrcs(header.arrOfCSRCs,
647 header.arrOfCSRCs + header.numCSRCs);
648 int decrypt_status = frame_decryptor_->Decrypt(
649 cricket::MEDIA_TYPE_AUDIO, csrcs,
650 /*additional_data=*/nullptr,
651 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
652 decrypted_audio_payload, &bytes_written);
653
654 // In this case just interpret the failure as a silent frame.
655 if (decrypt_status != 0) {
656 bytes_written = 0;
657 }
658
659 // Resize the decrypted audio payload to the number of bytes actually
660 // written.
661 decrypted_audio_payload.SetSize(bytes_written);
662 // Update the final payload.
663 payload = decrypted_audio_payload.data();
664 payload_data_length = decrypted_audio_payload.size();
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700665 } else if (crypto_options_.sframe.require_frame_encryption) {
666 RTC_DLOG(LS_ERROR)
667 << "FrameDecryptor required but not set, dropping packet";
668 payload_data_length = 0;
Benjamin Wright84583f62018-10-04 14:22:34 -0700669 }
670
Niels Möller530ead42018-10-04 14:28:39 +0200671 if (payload_data_length == 0) {
672 webrtc_rtp_header.frameType = kEmptyFrame;
673 return OnReceivedPayloadData(nullptr, 0, &webrtc_rtp_header);
674 }
675 return OnReceivedPayloadData(payload, payload_data_length,
676 &webrtc_rtp_header);
677}
678
Niels Möller349ade32018-11-16 09:50:42 +0100679// May be called on either worker thread or network thread.
Niels Möller80c67622018-11-12 13:22:47 +0100680// TODO(nisse): Drop always-true return value.
681bool ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200682 // Store playout timestamp for the received RTCP packet
683 UpdatePlayoutTimestamp(true);
684
685 // Deliver RTCP packet to RTP/RTCP module for parsing
686 _rtpRtcpModule->IncomingRtcpPacket(data, length);
687
688 int64_t rtt = GetRTT();
689 if (rtt == 0) {
690 // Waiting for valid RTT.
Niels Möller80c67622018-11-12 13:22:47 +0100691 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200692 }
693
694 int64_t nack_window_ms = rtt;
695 if (nack_window_ms < kMinRetransmissionWindowMs) {
696 nack_window_ms = kMinRetransmissionWindowMs;
697 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
698 nack_window_ms = kMaxRetransmissionWindowMs;
699 }
700
701 uint32_t ntp_secs = 0;
702 uint32_t ntp_frac = 0;
703 uint32_t rtp_timestamp = 0;
704 if (0 != _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
705 &rtp_timestamp)) {
706 // Waiting for RTCP.
Niels Möller80c67622018-11-12 13:22:47 +0100707 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200708 }
709
710 {
711 rtc::CritScope lock(&ts_stats_lock_);
712 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
713 }
Niels Möller80c67622018-11-12 13:22:47 +0100714 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200715}
716
717int ChannelReceive::GetSpeechOutputLevelFullRange() const {
Niels Möller349ade32018-11-16 09:50:42 +0100718 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200719 return _outputAudioLevel.LevelFullRange();
720}
721
722double ChannelReceive::GetTotalOutputEnergy() const {
Niels Möller349ade32018-11-16 09:50:42 +0100723 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200724 return _outputAudioLevel.TotalEnergy();
725}
726
727double ChannelReceive::GetTotalOutputDuration() const {
Niels Möller349ade32018-11-16 09:50:42 +0100728 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200729 return _outputAudioLevel.TotalDuration();
730}
731
732void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
Niels Möller349ade32018-11-16 09:50:42 +0100733 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200734 rtc::CritScope cs(&volume_settings_critsect_);
735 _outputGain = scaling;
736}
737
Niels Möller349ade32018-11-16 09:50:42 +0100738void ChannelReceive::SetLocalSSRC(uint32_t ssrc) {
739 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200740 _rtpRtcpModule->SetSSRC(ssrc);
Niels Möller530ead42018-10-04 14:28:39 +0200741}
742
Niels Möller530ead42018-10-04 14:28:39 +0200743void ChannelReceive::RegisterReceiverCongestionControlObjects(
744 PacketRouter* packet_router) {
Niels Möller349ade32018-11-16 09:50:42 +0100745 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200746 RTC_DCHECK(packet_router);
747 RTC_DCHECK(!packet_router_);
748 constexpr bool remb_candidate = false;
749 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get(), remb_candidate);
750 packet_router_ = packet_router;
751}
752
753void ChannelReceive::ResetReceiverCongestionControlObjects() {
Niels Möller349ade32018-11-16 09:50:42 +0100754 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200755 RTC_DCHECK(packet_router_);
756 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
757 packet_router_ = nullptr;
758}
759
Niels Möller349ade32018-11-16 09:50:42 +0100760CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
761 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200762 // --- RtcpStatistics
Niels Möller80c67622018-11-12 13:22:47 +0100763 CallReceiveStatistics stats;
Niels Möller530ead42018-10-04 14:28:39 +0200764
765 // The jitter statistics is updated for each received RTP packet and is
766 // based on received packets.
767 RtcpStatistics statistics;
768 StreamStatistician* statistician =
769 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
770 if (statistician) {
771 statistician->GetStatistics(&statistics,
772 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
773 }
774
775 stats.fractionLost = statistics.fraction_lost;
776 stats.cumulativeLost = statistics.packets_lost;
777 stats.extendedMax = statistics.extended_highest_sequence_number;
778 stats.jitterSamples = statistics.jitter;
779
780 // --- RTT
781 stats.rttMs = GetRTT();
782
783 // --- Data counters
784
785 size_t bytesReceived(0);
786 uint32_t packetsReceived(0);
787
788 if (statistician) {
789 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
790 }
791
792 stats.bytesReceived = bytesReceived;
793 stats.packetsReceived = packetsReceived;
794
795 // --- Timestamps
796 {
797 rtc::CritScope lock(&ts_stats_lock_);
798 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
799 }
Niels Möller80c67622018-11-12 13:22:47 +0100800 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200801}
802
Niels Möller349ade32018-11-16 09:50:42 +0100803void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
804 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200805 // None of these functions can fail.
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100806 if (enable) {
807 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
Niels Möller349ade32018-11-16 09:50:42 +0100808 audio_coding_->EnableNack(max_packets);
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100809 } else {
810 rtp_receive_statistics_->SetMaxReorderingThreshold(
811 kDefaultMaxReorderingThreshold);
Niels Möller530ead42018-10-04 14:28:39 +0200812 audio_coding_->DisableNack();
Danil Chapovalov2a977cf2018-12-04 18:03:52 +0100813 }
Niels Möller530ead42018-10-04 14:28:39 +0200814}
815
816// Called when we are missing one or more packets.
817int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
818 int length) {
819 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
820}
821
Niels Möllerdced9f62018-11-19 10:27:07 +0100822void ChannelReceive::SetAssociatedSendChannel(
823 const ChannelSendInterface* channel) {
Niels Möller349ade32018-11-16 09:50:42 +0100824 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200825 rtc::CritScope lock(&assoc_send_channel_lock_);
826 associated_send_channel_ = channel;
827}
828
Niels Möller80c67622018-11-12 13:22:47 +0100829NetworkStatistics ChannelReceive::GetNetworkStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100830 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100831 NetworkStatistics stats;
832 int error = audio_coding_->GetNetworkStatistics(&stats);
833 RTC_DCHECK_EQ(0, error);
834 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200835}
836
Niels Möller80c67622018-11-12 13:22:47 +0100837AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
Niels Möller349ade32018-11-16 09:50:42 +0100838 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread());
Niels Möller80c67622018-11-12 13:22:47 +0100839 AudioDecodingCallStats stats;
840 audio_coding_->GetDecodingCallStatistics(&stats);
841 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200842}
843
844uint32_t ChannelReceive::GetDelayEstimate() const {
Niels Möller349ade32018-11-16 09:50:42 +0100845 RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() ||
846 module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200847 rtc::CritScope lock(&video_sync_lock_);
848 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
849}
850
Niels Möller349ade32018-11-16 09:50:42 +0100851void ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
852 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
853 // Limit to range accepted by both VoE and ACM, so we're at least getting as
854 // close as possible, instead of failing.
855 delay_ms = rtc::SafeClamp(delay_ms, 0, 10000);
856 if ((delay_ms < kVoiceEngineMinMinPlayoutDelayMs) ||
857 (delay_ms > kVoiceEngineMaxMinPlayoutDelayMs)) {
Niels Möller530ead42018-10-04 14:28:39 +0200858 RTC_DLOG(LS_ERROR) << "SetMinimumPlayoutDelay() invalid min delay";
Niels Möller80c67622018-11-12 13:22:47 +0100859 return;
Niels Möller530ead42018-10-04 14:28:39 +0200860 }
Niels Möller349ade32018-11-16 09:50:42 +0100861 if (audio_coding_->SetMinimumPlayoutDelay(delay_ms) != 0) {
Niels Möller530ead42018-10-04 14:28:39 +0200862 RTC_DLOG(LS_ERROR)
863 << "SetMinimumPlayoutDelay() failed to set min playout delay";
Niels Möller530ead42018-10-04 14:28:39 +0200864 }
Niels Möller530ead42018-10-04 14:28:39 +0200865}
866
Niels Möller349ade32018-11-16 09:50:42 +0100867uint32_t ChannelReceive::GetPlayoutTimestamp() const {
868 RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200869 {
870 rtc::CritScope lock(&video_sync_lock_);
Niels Möller80c67622018-11-12 13:22:47 +0100871 return playout_timestamp_rtp_;
Niels Möller530ead42018-10-04 14:28:39 +0200872 }
Niels Möller530ead42018-10-04 14:28:39 +0200873}
874
875absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
Niels Möller349ade32018-11-16 09:50:42 +0100876 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
Niels Möller530ead42018-10-04 14:28:39 +0200877 Syncable::Info info;
878 if (_rtpRtcpModule->RemoteNTP(&info.capture_time_ntp_secs,
879 &info.capture_time_ntp_frac, nullptr, nullptr,
880 &info.capture_time_source_clock) != 0) {
881 return absl::nullopt;
882 }
883 {
884 rtc::CritScope cs(&rtp_sources_lock_);
885 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
886 return absl::nullopt;
887 }
888 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
889 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
890 }
891 return info;
892}
893
894void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp) {
895 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
896
897 if (!jitter_buffer_playout_timestamp_) {
898 // This can happen if this channel has not received any RTP packets. In
899 // this case, NetEq is not capable of computing a playout timestamp.
900 return;
901 }
902
903 uint16_t delay_ms = 0;
904 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
905 RTC_DLOG(LS_WARNING)
906 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
907 << " playout delay from the ADM";
908 return;
909 }
910
911 RTC_DCHECK(jitter_buffer_playout_timestamp_);
912 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
913
914 // Remove the playout delay.
915 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
916
917 {
918 rtc::CritScope lock(&video_sync_lock_);
919 if (!rtcp) {
920 playout_timestamp_rtp_ = playout_timestamp;
921 }
922 playout_delay_ms_ = delay_ms;
923 }
924}
925
926int ChannelReceive::GetRtpTimestampRateHz() const {
927 const auto format = audio_coding_->ReceiveFormat();
928 // Default to the playout frequency if we've not gotten any packets yet.
929 // TODO(ossu): Zero clockrate can only happen if we've added an external
930 // decoder for a format we don't support internally. Remove once that way of
931 // adding decoders is gone!
932 return (format && format->clockrate_hz != 0)
933 ? format->clockrate_hz
934 : audio_coding_->PlayoutFrequency();
935}
936
937int64_t ChannelReceive::GetRTT() const {
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800938 if (media_transport_) {
939 auto target_rate = media_transport_->GetLatestTargetTransferRate();
940 if (target_rate.has_value()) {
941 return target_rate->network_estimate.round_trip_time.ms();
942 }
943
944 return 0;
945 }
Niels Möller530ead42018-10-04 14:28:39 +0200946 RtcpMode method = _rtpRtcpModule->RTCP();
947 if (method == RtcpMode::kOff) {
948 return 0;
949 }
950 std::vector<RTCPReportBlock> report_blocks;
951 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
952
953 // TODO(nisse): Could we check the return value from the ->RTT() call below,
954 // instead of checking if we have any report blocks?
955 if (report_blocks.empty()) {
956 rtc::CritScope lock(&assoc_send_channel_lock_);
957 // Tries to get RTT from an associated channel.
958 if (!associated_send_channel_) {
959 return 0;
960 }
961 return associated_send_channel_->GetRTT();
962 }
963
964 int64_t rtt = 0;
965 int64_t avg_rtt = 0;
966 int64_t max_rtt = 0;
967 int64_t min_rtt = 0;
Niels Möllerfd1a2fb2018-10-31 15:25:26 +0100968 // TODO(nisse): This method computes RTT based on sender reports, even though
969 // a receive stream is not supposed to do that.
Niels Möller530ead42018-10-04 14:28:39 +0200970 if (_rtpRtcpModule->RTT(remote_ssrc_, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
971 0) {
972 return 0;
973 }
974 return rtt;
975}
976
Niels Möller349ade32018-11-16 09:50:42 +0100977} // namespace
978
979std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
980 ProcessThread* module_process_thread,
981 AudioDeviceModule* audio_device_module,
982 MediaTransportInterface* media_transport,
983 Transport* rtcp_send_transport,
984 RtcEventLog* rtc_event_log,
985 uint32_t remote_ssrc,
986 size_t jitter_buffer_max_packets,
987 bool jitter_buffer_fast_playout,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100988 int jitter_buffer_min_delay_ms,
Niels Möller349ade32018-11-16 09:50:42 +0100989 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
990 absl::optional<AudioCodecPairId> codec_pair_id,
991 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
992 const webrtc::CryptoOptions& crypto_options) {
993 return absl::make_unique<ChannelReceive>(
994 module_process_thread, audio_device_module, media_transport,
995 rtcp_send_transport, rtc_event_log, remote_ssrc,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100996 jitter_buffer_max_packets, jitter_buffer_fast_playout,
997 jitter_buffer_min_delay_ms, decoder_factory, codec_pair_id,
998 frame_decryptor, crypto_options);
Niels Möller349ade32018-11-16 09:50:42 +0100999}
1000
Niels Möller530ead42018-10-04 14:28:39 +02001001} // namespace voe
1002} // namespace webrtc