1 /*
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 "api/crypto/frame_decryptor_interface.h"
21 #include "api/frame_transformer_interface.h"
22 #include "api/rtc_event_log/rtc_event_log.h"
23 #include "api/sequence_checker.h"
24 #include "api/task_queue/pending_task_safety_flag.h"
25 #include "api/task_queue/task_queue_base.h"
26 #include "api/units/time_delta.h"
27 #include "audio/audio_level.h"
28 #include "audio/channel_receive_frame_transformer_delegate.h"
29 #include "audio/channel_send.h"
30 #include "audio/utility/audio_frame_operations.h"
31 #include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
32 #include "modules/audio_coding/acm2/acm_receiver.h"
33 #include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
34 #include "modules/audio_device/include/audio_device.h"
35 #include "modules/pacing/packet_router.h"
36 #include "modules/rtp_rtcp/include/receive_statistics.h"
37 #include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
38 #include "modules/rtp_rtcp/source/absolute_capture_time_interpolator.h"
39 #include "modules/rtp_rtcp/source/capture_clock_offset_updater.h"
40 #include "modules/rtp_rtcp/source/rtp_header_extensions.h"
41 #include "modules/rtp_rtcp/source/rtp_packet_received.h"
42 #include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
43 #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
44 #include "rtc_base/checks.h"
45 #include "rtc_base/logging.h"
46 #include "rtc_base/numerics/safe_minmax.h"
47 #include "rtc_base/race_checker.h"
48 #include "rtc_base/synchronization/mutex.h"
49 #include "rtc_base/system/no_unique_address.h"
50 #include "rtc_base/time_utils.h"
51 #include "rtc_base/trace_event.h"
52 #include "system_wrappers/include/metrics.h"
53 #include "system_wrappers/include/ntp_time.h"
54
55 namespace webrtc {
56 namespace voe {
57
58 namespace {
59
60 constexpr double kAudioSampleDurationSeconds = 0.01;
61
62 // Video Sync.
63 constexpr int kVoiceEngineMinMinPlayoutDelayMs = 0;
64 constexpr int kVoiceEngineMaxMinPlayoutDelayMs = 10000;
65
AcmConfig(NetEqFactory * neteq_factory,rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,absl::optional<AudioCodecPairId> codec_pair_id,size_t jitter_buffer_max_packets,bool jitter_buffer_fast_playout)66 AudioCodingModule::Config AcmConfig(
67 NetEqFactory* neteq_factory,
68 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
69 absl::optional<AudioCodecPairId> codec_pair_id,
70 size_t jitter_buffer_max_packets,
71 bool jitter_buffer_fast_playout) {
72 AudioCodingModule::Config acm_config;
73 acm_config.neteq_factory = neteq_factory;
74 acm_config.decoder_factory = decoder_factory;
75 acm_config.neteq_config.codec_pair_id = codec_pair_id;
76 acm_config.neteq_config.max_packets_in_buffer = jitter_buffer_max_packets;
77 acm_config.neteq_config.enable_fast_accelerate = jitter_buffer_fast_playout;
78 acm_config.neteq_config.enable_muted_state = true;
79
80 return acm_config;
81 }
82
83 class ChannelReceive : public ChannelReceiveInterface,
84 public RtcpPacketTypeCounterObserver {
85 public:
86 // Used for receive streams.
87 ChannelReceive(
88 Clock* clock,
89 NetEqFactory* neteq_factory,
90 AudioDeviceModule* audio_device_module,
91 Transport* rtcp_send_transport,
92 RtcEventLog* rtc_event_log,
93 uint32_t local_ssrc,
94 uint32_t remote_ssrc,
95 size_t jitter_buffer_max_packets,
96 bool jitter_buffer_fast_playout,
97 int jitter_buffer_min_delay_ms,
98 bool enable_non_sender_rtt,
99 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
100 absl::optional<AudioCodecPairId> codec_pair_id,
101 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
102 const webrtc::CryptoOptions& crypto_options,
103 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer);
104 ~ChannelReceive() override;
105
106 void SetSink(AudioSinkInterface* sink) override;
107
108 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
109
110 // API methods
111
112 void StartPlayout() override;
113 void StopPlayout() override;
114
115 // Codecs
116 absl::optional<std::pair<int, SdpAudioFormat>> GetReceiveCodec()
117 const override;
118
119 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
120
121 // RtpPacketSinkInterface.
122 void OnRtpPacket(const RtpPacketReceived& packet) override;
123
124 // Muting, Volume and Level.
125 void SetChannelOutputVolumeScaling(float scaling) override;
126 int GetSpeechOutputLevelFullRange() const override;
127 // See description of "totalAudioEnergy" in the WebRTC stats spec:
128 // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
129 double GetTotalOutputEnergy() const override;
130 double GetTotalOutputDuration() const override;
131
132 // Stats.
133 NetworkStatistics GetNetworkStatistics(
134 bool get_and_clear_legacy_stats) const override;
135 AudioDecodingCallStats GetDecodingCallStatistics() const override;
136
137 // Audio+Video Sync.
138 uint32_t GetDelayEstimate() const override;
139 bool SetMinimumPlayoutDelay(int delayMs) override;
140 bool GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
141 int64_t* time_ms) const override;
142 void SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
143 int64_t time_ms) override;
144 absl::optional<int64_t> GetCurrentEstimatedPlayoutNtpTimestampMs(
145 int64_t now_ms) const override;
146
147 // Audio quality.
148 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
149 int GetBaseMinimumPlayoutDelayMs() const override;
150
151 // Produces the transport-related timestamps; current_delay_ms is left unset.
152 absl::optional<Syncable::Info> GetSyncInfo() const override;
153
154 void RegisterReceiverCongestionControlObjects(
155 PacketRouter* packet_router) override;
156 void ResetReceiverCongestionControlObjects() override;
157
158 CallReceiveStatistics GetRTCPStatistics() const override;
159 void SetNACKStatus(bool enable, int maxNumberOfPackets) override;
160 void SetNonSenderRttMeasurement(bool enabled) 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 void SetSourceTracker(SourceTracker* source_tracker) override;
169
170 // Associate to a send channel.
171 // Used for obtaining RTT for a receive-only channel.
172 void SetAssociatedSendChannel(const ChannelSendInterface* channel) override;
173
174 // Sets a frame transformer between the depacketizer and the decoder, to
175 // transform the received frames before decoding them.
176 void SetDepacketizerToDecoderFrameTransformer(
177 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)
178 override;
179
180 void SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface>
181 frame_decryptor) override;
182
183 void OnLocalSsrcChange(uint32_t local_ssrc) override;
184 uint32_t GetLocalSsrc() const override;
185
186 void RtcpPacketTypesCounterUpdated(
187 uint32_t ssrc,
188 const RtcpPacketTypeCounter& packet_counter) override;
189
190 private:
191 void ReceivePacket(const uint8_t* packet,
192 size_t packet_length,
193 const RTPHeader& header)
194 RTC_RUN_ON(worker_thread_checker_);
195 int ResendPackets(const uint16_t* sequence_numbers, int length);
196 void UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms)
197 RTC_RUN_ON(worker_thread_checker_);
198
199 int GetRtpTimestampRateHz() const;
200
201 void OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,
202 const RTPHeader& rtpHeader)
203 RTC_RUN_ON(worker_thread_checker_);
204
205 void InitFrameTransformerDelegate(
206 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)
207 RTC_RUN_ON(worker_thread_checker_);
208
209 // Thread checkers document and lock usage of some methods to specific threads
210 // we know about. The goal is to eventually split up voe::ChannelReceive into
211 // parts with single-threaded semantics, and thereby reduce the need for
212 // locks.
213 RTC_NO_UNIQUE_ADDRESS SequenceChecker worker_thread_checker_;
214 RTC_NO_UNIQUE_ADDRESS SequenceChecker network_thread_checker_;
215
216 TaskQueueBase* const worker_thread_;
217 ScopedTaskSafety worker_safety_;
218
219 // Methods accessed from audio and video threads are checked for sequential-
220 // only access. We don't necessarily own and control these threads, so thread
221 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
222 // audio thread to another, but access is still sequential.
223 rtc::RaceChecker audio_thread_race_checker_;
224 Mutex callback_mutex_;
225 Mutex volume_settings_mutex_;
226
227 bool playing_ RTC_GUARDED_BY(worker_thread_checker_) = false;
228
229 RtcEventLog* const event_log_;
230
231 // Indexed by payload type.
232 std::map<uint8_t, int> payload_type_frequencies_;
233
234 std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;
235 std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_;
236 const uint32_t remote_ssrc_;
237 SourceTracker* source_tracker_ = nullptr;
238
239 // Info for GetSyncInfo is updated on network or worker thread, and queried on
240 // the worker thread.
241 absl::optional<uint32_t> last_received_rtp_timestamp_
242 RTC_GUARDED_BY(&worker_thread_checker_);
243 absl::optional<int64_t> last_received_rtp_system_time_ms_
244 RTC_GUARDED_BY(&worker_thread_checker_);
245
246 // The AcmReceiver is thread safe, using its own lock.
247 acm2::AcmReceiver acm_receiver_;
248 AudioSinkInterface* audio_sink_ = nullptr;
249 AudioLevel _outputAudioLevel;
250
251 Clock* const clock_;
252 RemoteNtpTimeEstimator ntp_estimator_ RTC_GUARDED_BY(ts_stats_lock_);
253
254 // Timestamp of the audio pulled from NetEq.
255 absl::optional<uint32_t> jitter_buffer_playout_timestamp_;
256
257 uint32_t playout_timestamp_rtp_ RTC_GUARDED_BY(worker_thread_checker_);
258 absl::optional<int64_t> playout_timestamp_rtp_time_ms_
259 RTC_GUARDED_BY(worker_thread_checker_);
260 uint32_t playout_delay_ms_ RTC_GUARDED_BY(worker_thread_checker_);
261 absl::optional<int64_t> playout_timestamp_ntp_
262 RTC_GUARDED_BY(worker_thread_checker_);
263 absl::optional<int64_t> playout_timestamp_ntp_time_ms_
264 RTC_GUARDED_BY(worker_thread_checker_);
265
266 mutable Mutex ts_stats_lock_;
267
268 std::unique_ptr<rtc::TimestampWrapAroundHandler> rtp_ts_wraparound_handler_;
269 // The rtp timestamp of the first played out audio frame.
270 int64_t capture_start_rtp_time_stamp_;
271 // The capture ntp time (in local timebase) of the first played out audio
272 // frame.
273 int64_t capture_start_ntp_time_ms_ RTC_GUARDED_BY(ts_stats_lock_);
274
275 AudioDeviceModule* _audioDeviceModulePtr;
276 float _outputGain RTC_GUARDED_BY(volume_settings_mutex_);
277
278 const ChannelSendInterface* associated_send_channel_
279 RTC_GUARDED_BY(network_thread_checker_);
280
281 PacketRouter* packet_router_ = nullptr;
282
283 SequenceChecker construction_thread_;
284
285 // E2EE Audio Frame Decryption
286 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor_
287 RTC_GUARDED_BY(worker_thread_checker_);
288 webrtc::CryptoOptions crypto_options_;
289
290 webrtc::AbsoluteCaptureTimeInterpolator absolute_capture_time_interpolator_
291 RTC_GUARDED_BY(worker_thread_checker_);
292
293 webrtc::CaptureClockOffsetUpdater capture_clock_offset_updater_;
294
295 rtc::scoped_refptr<ChannelReceiveFrameTransformerDelegate>
296 frame_transformer_delegate_;
297
298 // Counter that's used to control the frequency of reporting histograms
299 // from the `GetAudioFrameWithInfo` callback.
300 int audio_frame_interval_count_ RTC_GUARDED_BY(audio_thread_race_checker_) =
301 0;
302 // Controls how many callbacks we let pass by before reporting callback stats.
303 // A value of 100 means 100 callbacks, each one of which represents 10ms worth
304 // of data, so the stats reporting frequency will be 1Hz (modulo failures).
305 constexpr static int kHistogramReportingInterval = 100;
306
307 mutable Mutex rtcp_counter_mutex_;
308 RtcpPacketTypeCounter rtcp_packet_type_counter_
309 RTC_GUARDED_BY(rtcp_counter_mutex_);
310 };
311
OnReceivedPayloadData(rtc::ArrayView<const uint8_t> payload,const RTPHeader & rtpHeader)312 void ChannelReceive::OnReceivedPayloadData(
313 rtc::ArrayView<const uint8_t> payload,
314 const RTPHeader& rtpHeader) {
315 if (!playing_) {
316 // Avoid inserting into NetEQ when we are not playing. Count the
317 // packet as discarded.
318
319 // If we have a source_tracker_, tell it that the frame has been
320 // "delivered". Normally, this happens in AudioReceiveStreamInterface when
321 // audio frames are pulled out, but when playout is muted, nothing is
322 // pulling frames. The downside of this approach is that frames delivered
323 // this way won't be delayed for playout, and therefore will be
324 // unsynchronized with (a) audio delay when playing and (b) any audio/video
325 // synchronization. But the alternative is that muting playout also stops
326 // the SourceTracker from updating RtpSource information.
327 if (source_tracker_) {
328 RtpPacketInfos::vector_type packet_vector = {
329 RtpPacketInfo(rtpHeader, clock_->CurrentTime())};
330 source_tracker_->OnFrameDelivered(RtpPacketInfos(packet_vector));
331 }
332
333 return;
334 }
335
336 // Push the incoming payload (parsed and ready for decoding) into the ACM
337 if (acm_receiver_.InsertPacket(rtpHeader, payload) != 0) {
338 RTC_DLOG(LS_ERROR) << "ChannelReceive::OnReceivedPayloadData() unable to "
339 "push data to the ACM";
340 return;
341 }
342
343 int64_t round_trip_time = 0;
344 rtp_rtcp_->RTT(remote_ssrc_, &round_trip_time, /*avg_rtt=*/nullptr,
345 /*min_rtt=*/nullptr, /*max_rtt=*/nullptr);
346
347 std::vector<uint16_t> nack_list = acm_receiver_.GetNackList(round_trip_time);
348 if (!nack_list.empty()) {
349 // Can't use nack_list.data() since it's not supported by all
350 // compilers.
351 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
352 }
353 }
354
InitFrameTransformerDelegate(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)355 void ChannelReceive::InitFrameTransformerDelegate(
356 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
357 RTC_DCHECK(frame_transformer);
358 RTC_DCHECK(!frame_transformer_delegate_);
359 RTC_DCHECK(worker_thread_->IsCurrent());
360
361 // Pass a callback to ChannelReceive::OnReceivedPayloadData, to be called by
362 // the delegate to receive transformed audio.
363 ChannelReceiveFrameTransformerDelegate::ReceiveFrameCallback
364 receive_audio_callback = [this](rtc::ArrayView<const uint8_t> packet,
365 const RTPHeader& header) {
366 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
367 OnReceivedPayloadData(packet, header);
368 };
369 frame_transformer_delegate_ =
370 rtc::make_ref_counted<ChannelReceiveFrameTransformerDelegate>(
371 std::move(receive_audio_callback), std::move(frame_transformer),
372 worker_thread_);
373 frame_transformer_delegate_->Init();
374 }
375
GetAudioFrameWithInfo(int sample_rate_hz,AudioFrame * audio_frame)376 AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo(
377 int sample_rate_hz,
378 AudioFrame* audio_frame) {
379 TRACE_EVENT_BEGIN1("webrtc", "ChannelReceive::GetAudioFrameWithInfo",
380 "sample_rate_hz", sample_rate_hz);
381 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
382 audio_frame->sample_rate_hz_ = sample_rate_hz;
383
384 event_log_->Log(std::make_unique<RtcEventAudioPlayout>(remote_ssrc_));
385
386 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
387 bool muted;
388 if (acm_receiver_.GetAudio(audio_frame->sample_rate_hz_, audio_frame,
389 &muted) == -1) {
390 RTC_DLOG(LS_ERROR)
391 << "ChannelReceive::GetAudioFrame() PlayoutData10Ms() failed!";
392 // In all likelihood, the audio in this frame is garbage. We return an
393 // error so that the audio mixer module doesn't add it to the mix. As
394 // a result, it won't be played out and the actions skipped here are
395 // irrelevant.
396
397 TRACE_EVENT_END1("webrtc", "ChannelReceive::GetAudioFrameWithInfo", "error",
398 1);
399 return AudioMixer::Source::AudioFrameInfo::kError;
400 }
401
402 if (muted) {
403 // TODO(henrik.lundin): We should be able to do better than this. But we
404 // will have to go through all the cases below where the audio samples may
405 // be used, and handle the muted case in some way.
406 AudioFrameOperations::Mute(audio_frame);
407 }
408
409 {
410 // Pass the audio buffers to an optional sink callback, before applying
411 // scaling/panning, as that applies to the mix operation.
412 // External recipients of the audio (e.g. via AudioTrack), will do their
413 // own mixing/dynamic processing.
414 MutexLock lock(&callback_mutex_);
415 if (audio_sink_) {
416 AudioSinkInterface::Data data(
417 audio_frame->data(), audio_frame->samples_per_channel_,
418 audio_frame->sample_rate_hz_, audio_frame->num_channels_,
419 audio_frame->timestamp_);
420 audio_sink_->OnData(data);
421 }
422 }
423
424 float output_gain = 1.0f;
425 {
426 MutexLock lock(&volume_settings_mutex_);
427 output_gain = _outputGain;
428 }
429
430 // Output volume scaling
431 if (output_gain < 0.99f || output_gain > 1.01f) {
432 // TODO(solenberg): Combine with mute state - this can cause clicks!
433 AudioFrameOperations::ScaleWithSat(output_gain, audio_frame);
434 }
435
436 // Measure audio level (0-9)
437 // TODO(henrik.lundin) Use the `muted` information here too.
438 // TODO(deadbeef): Use RmsLevel for `_outputAudioLevel` (see
439 // https://crbug.com/webrtc/7517).
440 _outputAudioLevel.ComputeLevel(*audio_frame, kAudioSampleDurationSeconds);
441
442 if (capture_start_rtp_time_stamp_ < 0 && audio_frame->timestamp_ != 0) {
443 // The first frame with a valid rtp timestamp.
444 capture_start_rtp_time_stamp_ = audio_frame->timestamp_;
445 }
446
447 if (capture_start_rtp_time_stamp_ >= 0) {
448 // audio_frame.timestamp_ should be valid from now on.
449 // Compute elapsed time.
450 int64_t unwrap_timestamp =
451 rtp_ts_wraparound_handler_->Unwrap(audio_frame->timestamp_);
452 audio_frame->elapsed_time_ms_ =
453 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
454 (GetRtpTimestampRateHz() / 1000);
455
456 {
457 MutexLock lock(&ts_stats_lock_);
458 // Compute ntp time.
459 audio_frame->ntp_time_ms_ =
460 ntp_estimator_.Estimate(audio_frame->timestamp_);
461 // `ntp_time_ms_` won't be valid until at least 2 RTCP SRs are received.
462 if (audio_frame->ntp_time_ms_ > 0) {
463 // Compute `capture_start_ntp_time_ms_` so that
464 // `capture_start_ntp_time_ms_` + `elapsed_time_ms_` == `ntp_time_ms_`
465 capture_start_ntp_time_ms_ =
466 audio_frame->ntp_time_ms_ - audio_frame->elapsed_time_ms_;
467 }
468 }
469 }
470
471 // Fill in local capture clock offset in `audio_frame->packet_infos_`.
472 RtpPacketInfos::vector_type packet_infos;
473 for (auto& packet_info : audio_frame->packet_infos_) {
474 absl::optional<int64_t> local_capture_clock_offset_q32x32;
475 if (packet_info.absolute_capture_time().has_value()) {
476 local_capture_clock_offset_q32x32 =
477 capture_clock_offset_updater_.AdjustEstimatedCaptureClockOffset(
478 packet_info.absolute_capture_time()
479 ->estimated_capture_clock_offset);
480 }
481 RtpPacketInfo new_packet_info(packet_info);
482 absl::optional<TimeDelta> local_capture_clock_offset;
483 if (local_capture_clock_offset_q32x32.has_value()) {
484 local_capture_clock_offset = TimeDelta::Millis(
485 UQ32x32ToInt64Ms(*local_capture_clock_offset_q32x32));
486 }
487 new_packet_info.set_local_capture_clock_offset(local_capture_clock_offset);
488 packet_infos.push_back(std::move(new_packet_info));
489 }
490 audio_frame->packet_infos_ = RtpPacketInfos(packet_infos);
491
492 ++audio_frame_interval_count_;
493 if (audio_frame_interval_count_ >= kHistogramReportingInterval) {
494 audio_frame_interval_count_ = 0;
495 worker_thread_->PostTask(SafeTask(worker_safety_.flag(), [this]() {
496 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
497 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.TargetJitterBufferDelayMs",
498 acm_receiver_.TargetDelayMs());
499 const int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
500 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDelayEstimateMs",
501 jitter_buffer_delay + playout_delay_ms_);
502 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverJitterBufferDelayMs",
503 jitter_buffer_delay);
504 RTC_HISTOGRAM_COUNTS_1000("WebRTC.Audio.ReceiverDeviceDelayMs",
505 playout_delay_ms_);
506 }));
507 }
508
509 TRACE_EVENT_END2("webrtc", "ChannelReceive::GetAudioFrameWithInfo", "gain",
510 output_gain, "muted", muted);
511 return muted ? AudioMixer::Source::AudioFrameInfo::kMuted
512 : AudioMixer::Source::AudioFrameInfo::kNormal;
513 }
514
PreferredSampleRate() const515 int ChannelReceive::PreferredSampleRate() const {
516 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
517 // Return the bigger of playout and receive frequency in the ACM.
518 return std::max(acm_receiver_.last_packet_sample_rate_hz().value_or(0),
519 acm_receiver_.last_output_sample_rate_hz());
520 }
521
SetSourceTracker(SourceTracker * source_tracker)522 void ChannelReceive::SetSourceTracker(SourceTracker* source_tracker) {
523 source_tracker_ = source_tracker;
524 }
525
ChannelReceive(Clock * clock,NetEqFactory * neteq_factory,AudioDeviceModule * audio_device_module,Transport * rtcp_send_transport,RtcEventLog * rtc_event_log,uint32_t local_ssrc,uint32_t remote_ssrc,size_t jitter_buffer_max_packets,bool jitter_buffer_fast_playout,int jitter_buffer_min_delay_ms,bool enable_non_sender_rtt,rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,absl::optional<AudioCodecPairId> codec_pair_id,rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,const webrtc::CryptoOptions & crypto_options,rtc::scoped_refptr<FrameTransformerInterface> frame_transformer)526 ChannelReceive::ChannelReceive(
527 Clock* clock,
528 NetEqFactory* neteq_factory,
529 AudioDeviceModule* audio_device_module,
530 Transport* rtcp_send_transport,
531 RtcEventLog* rtc_event_log,
532 uint32_t local_ssrc,
533 uint32_t remote_ssrc,
534 size_t jitter_buffer_max_packets,
535 bool jitter_buffer_fast_playout,
536 int jitter_buffer_min_delay_ms,
537 bool enable_non_sender_rtt,
538 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
539 absl::optional<AudioCodecPairId> codec_pair_id,
540 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
541 const webrtc::CryptoOptions& crypto_options,
542 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer)
543 : worker_thread_(TaskQueueBase::Current()),
544 event_log_(rtc_event_log),
545 rtp_receive_statistics_(ReceiveStatistics::Create(clock)),
546 remote_ssrc_(remote_ssrc),
547 acm_receiver_(AcmConfig(neteq_factory,
548 decoder_factory,
549 codec_pair_id,
550 jitter_buffer_max_packets,
551 jitter_buffer_fast_playout)),
552 _outputAudioLevel(),
553 clock_(clock),
554 ntp_estimator_(clock),
555 playout_timestamp_rtp_(0),
556 playout_delay_ms_(0),
557 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
558 capture_start_rtp_time_stamp_(-1),
559 capture_start_ntp_time_ms_(-1),
560 _audioDeviceModulePtr(audio_device_module),
561 _outputGain(1.0f),
562 associated_send_channel_(nullptr),
563 frame_decryptor_(frame_decryptor),
564 crypto_options_(crypto_options),
565 absolute_capture_time_interpolator_(clock) {
566 RTC_DCHECK(audio_device_module);
567
568 network_thread_checker_.Detach();
569
570 acm_receiver_.ResetInitialDelay();
571 acm_receiver_.SetMinimumDelay(0);
572 acm_receiver_.SetMaximumDelay(0);
573 acm_receiver_.FlushBuffers();
574
575 _outputAudioLevel.ResetLevelFullRange();
576
577 rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc_, true);
578 RtpRtcpInterface::Configuration configuration;
579 configuration.clock = clock;
580 configuration.audio = true;
581 configuration.receiver_only = true;
582 configuration.outgoing_transport = rtcp_send_transport;
583 configuration.receive_statistics = rtp_receive_statistics_.get();
584 configuration.event_log = event_log_;
585 configuration.local_media_ssrc = local_ssrc;
586 configuration.rtcp_packet_type_counter_observer = this;
587 configuration.non_sender_rtt_measurement = enable_non_sender_rtt;
588
589 if (frame_transformer)
590 InitFrameTransformerDelegate(std::move(frame_transformer));
591
592 rtp_rtcp_ = ModuleRtpRtcpImpl2::Create(configuration);
593 rtp_rtcp_->SetRemoteSSRC(remote_ssrc_);
594
595 // Ensure that RTCP is enabled for the created channel.
596 rtp_rtcp_->SetRTCPStatus(RtcpMode::kCompound);
597 }
598
~ChannelReceive()599 ChannelReceive::~ChannelReceive() {
600 RTC_DCHECK_RUN_ON(&construction_thread_);
601
602 // Resets the delegate's callback to ChannelReceive::OnReceivedPayloadData.
603 if (frame_transformer_delegate_)
604 frame_transformer_delegate_->Reset();
605
606 StopPlayout();
607 }
608
SetSink(AudioSinkInterface * sink)609 void ChannelReceive::SetSink(AudioSinkInterface* sink) {
610 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
611 MutexLock lock(&callback_mutex_);
612 audio_sink_ = sink;
613 }
614
StartPlayout()615 void ChannelReceive::StartPlayout() {
616 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
617 playing_ = true;
618 }
619
StopPlayout()620 void ChannelReceive::StopPlayout() {
621 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
622 playing_ = false;
623 _outputAudioLevel.ResetLevelFullRange();
624 }
625
GetReceiveCodec() const626 absl::optional<std::pair<int, SdpAudioFormat>> ChannelReceive::GetReceiveCodec()
627 const {
628 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
629 return acm_receiver_.LastDecoder();
630 }
631
SetReceiveCodecs(const std::map<int,SdpAudioFormat> & codecs)632 void ChannelReceive::SetReceiveCodecs(
633 const std::map<int, SdpAudioFormat>& codecs) {
634 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
635 for (const auto& kv : codecs) {
636 RTC_DCHECK_GE(kv.second.clockrate_hz, 1000);
637 payload_type_frequencies_[kv.first] = kv.second.clockrate_hz;
638 }
639 acm_receiver_.SetCodecs(codecs);
640 }
641
OnRtpPacket(const RtpPacketReceived & packet)642 void ChannelReceive::OnRtpPacket(const RtpPacketReceived& packet) {
643 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
644 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
645 // network thread. Once that's done, the same applies to
646 // UpdatePlayoutTimestamp and
647 int64_t now_ms = rtc::TimeMillis();
648
649 last_received_rtp_timestamp_ = packet.Timestamp();
650 last_received_rtp_system_time_ms_ = now_ms;
651
652 // Store playout timestamp for the received RTP packet
653 UpdatePlayoutTimestamp(false, now_ms);
654
655 const auto& it = payload_type_frequencies_.find(packet.PayloadType());
656 if (it == payload_type_frequencies_.end())
657 return;
658 // TODO(bugs.webrtc.org/7135): Set payload_type_frequency earlier, when packet
659 // is parsed.
660 RtpPacketReceived packet_copy(packet);
661 packet_copy.set_payload_type_frequency(it->second);
662
663 rtp_receive_statistics_->OnRtpPacket(packet_copy);
664
665 RTPHeader header;
666 packet_copy.GetHeader(&header);
667
668 // Interpolates absolute capture timestamp RTP header extension.
669 header.extension.absolute_capture_time =
670 absolute_capture_time_interpolator_.OnReceivePacket(
671 AbsoluteCaptureTimeInterpolator::GetSource(header.ssrc,
672 header.arrOfCSRCs),
673 header.timestamp,
674 rtc::saturated_cast<uint32_t>(packet_copy.payload_type_frequency()),
675 header.extension.absolute_capture_time);
676
677 ReceivePacket(packet_copy.data(), packet_copy.size(), header);
678 }
679
ReceivePacket(const uint8_t * packet,size_t packet_length,const RTPHeader & header)680 void ChannelReceive::ReceivePacket(const uint8_t* packet,
681 size_t packet_length,
682 const RTPHeader& header) {
683 const uint8_t* payload = packet + header.headerLength;
684 RTC_DCHECK_GE(packet_length, header.headerLength);
685 size_t payload_length = packet_length - header.headerLength;
686
687 size_t payload_data_length = payload_length - header.paddingLength;
688
689 // E2EE Custom Audio Frame Decryption (This is optional).
690 // Keep this buffer around for the lifetime of the OnReceivedPayloadData call.
691 rtc::Buffer decrypted_audio_payload;
692 if (frame_decryptor_ != nullptr) {
693 const size_t max_plaintext_size = frame_decryptor_->GetMaxPlaintextByteSize(
694 cricket::MEDIA_TYPE_AUDIO, payload_length);
695 decrypted_audio_payload.SetSize(max_plaintext_size);
696
697 const std::vector<uint32_t> csrcs(header.arrOfCSRCs,
698 header.arrOfCSRCs + header.numCSRCs);
699 const FrameDecryptorInterface::Result decrypt_result =
700 frame_decryptor_->Decrypt(
701 cricket::MEDIA_TYPE_AUDIO, csrcs,
702 /*additional_data=*/nullptr,
703 rtc::ArrayView<const uint8_t>(payload, payload_data_length),
704 decrypted_audio_payload);
705
706 if (decrypt_result.IsOk()) {
707 decrypted_audio_payload.SetSize(decrypt_result.bytes_written);
708 } else {
709 // Interpret failures as a silent frame.
710 decrypted_audio_payload.SetSize(0);
711 }
712
713 payload = decrypted_audio_payload.data();
714 payload_data_length = decrypted_audio_payload.size();
715 } else if (crypto_options_.sframe.require_frame_encryption) {
716 RTC_DLOG(LS_ERROR)
717 << "FrameDecryptor required but not set, dropping packet";
718 payload_data_length = 0;
719 }
720
721 rtc::ArrayView<const uint8_t> payload_data(payload, payload_data_length);
722 if (frame_transformer_delegate_) {
723 // Asynchronously transform the received payload. After the payload is
724 // transformed, the delegate will call OnReceivedPayloadData to handle it.
725 frame_transformer_delegate_->Transform(payload_data, header, remote_ssrc_);
726 } else {
727 OnReceivedPayloadData(payload_data, header);
728 }
729 }
730
ReceivedRTCPPacket(const uint8_t * data,size_t length)731 void ChannelReceive::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
732 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
733 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
734 // network thread.
735
736 // Store playout timestamp for the received RTCP packet
737 UpdatePlayoutTimestamp(true, rtc::TimeMillis());
738
739 // Deliver RTCP packet to RTP/RTCP module for parsing
740 rtp_rtcp_->IncomingRtcpPacket(data, length);
741
742 int64_t rtt = 0;
743 rtp_rtcp_->RTT(remote_ssrc_, &rtt, /*avg_rtt=*/nullptr, /*min_rtt=*/nullptr,
744 /*max_rtt=*/nullptr);
745 if (rtt == 0) {
746 // Waiting for valid RTT.
747 return;
748 }
749
750 uint32_t ntp_secs = 0;
751 uint32_t ntp_frac = 0;
752 uint32_t rtp_timestamp = 0;
753 if (rtp_rtcp_->RemoteNTP(&ntp_secs, &ntp_frac,
754 /*rtcp_arrival_time_secs=*/nullptr,
755 /*rtcp_arrival_time_frac=*/nullptr,
756 &rtp_timestamp) != 0) {
757 // Waiting for RTCP.
758 return;
759 }
760
761 {
762 MutexLock lock(&ts_stats_lock_);
763 ntp_estimator_.UpdateRtcpTimestamp(
764 TimeDelta::Millis(rtt), NtpTime(ntp_secs, ntp_frac), rtp_timestamp);
765 absl::optional<int64_t> remote_to_local_clock_offset =
766 ntp_estimator_.EstimateRemoteToLocalClockOffset();
767 if (remote_to_local_clock_offset.has_value()) {
768 capture_clock_offset_updater_.SetRemoteToLocalClockOffset(
769 *remote_to_local_clock_offset);
770 }
771 }
772 }
773
GetSpeechOutputLevelFullRange() const774 int ChannelReceive::GetSpeechOutputLevelFullRange() const {
775 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
776 return _outputAudioLevel.LevelFullRange();
777 }
778
GetTotalOutputEnergy() const779 double ChannelReceive::GetTotalOutputEnergy() const {
780 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
781 return _outputAudioLevel.TotalEnergy();
782 }
783
GetTotalOutputDuration() const784 double ChannelReceive::GetTotalOutputDuration() const {
785 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
786 return _outputAudioLevel.TotalDuration();
787 }
788
SetChannelOutputVolumeScaling(float scaling)789 void ChannelReceive::SetChannelOutputVolumeScaling(float scaling) {
790 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
791 MutexLock lock(&volume_settings_mutex_);
792 _outputGain = scaling;
793 }
794
RegisterReceiverCongestionControlObjects(PacketRouter * packet_router)795 void ChannelReceive::RegisterReceiverCongestionControlObjects(
796 PacketRouter* packet_router) {
797 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
798 RTC_DCHECK(packet_router);
799 RTC_DCHECK(!packet_router_);
800 constexpr bool remb_candidate = false;
801 packet_router->AddReceiveRtpModule(rtp_rtcp_.get(), remb_candidate);
802 packet_router_ = packet_router;
803 }
804
ResetReceiverCongestionControlObjects()805 void ChannelReceive::ResetReceiverCongestionControlObjects() {
806 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
807 RTC_DCHECK(packet_router_);
808 packet_router_->RemoveReceiveRtpModule(rtp_rtcp_.get());
809 packet_router_ = nullptr;
810 }
811
GetRTCPStatistics() const812 CallReceiveStatistics ChannelReceive::GetRTCPStatistics() const {
813 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
814 CallReceiveStatistics stats;
815
816 // The jitter statistics is updated for each received RTP packet and is based
817 // on received packets.
818 RtpReceiveStats rtp_stats;
819 StreamStatistician* statistician =
820 rtp_receive_statistics_->GetStatistician(remote_ssrc_);
821 if (statistician) {
822 rtp_stats = statistician->GetStats();
823 }
824
825 stats.cumulativeLost = rtp_stats.packets_lost;
826 stats.jitterSamples = rtp_stats.jitter;
827
828 // Data counters.
829 if (statistician) {
830 stats.payload_bytes_rcvd = rtp_stats.packet_counter.payload_bytes;
831
832 stats.header_and_padding_bytes_rcvd =
833 rtp_stats.packet_counter.header_bytes +
834 rtp_stats.packet_counter.padding_bytes;
835 stats.packetsReceived = rtp_stats.packet_counter.packets;
836 stats.last_packet_received_timestamp_ms =
837 rtp_stats.last_packet_received_timestamp_ms;
838 } else {
839 stats.payload_bytes_rcvd = 0;
840 stats.header_and_padding_bytes_rcvd = 0;
841 stats.packetsReceived = 0;
842 stats.last_packet_received_timestamp_ms = absl::nullopt;
843 }
844
845 {
846 MutexLock lock(&rtcp_counter_mutex_);
847 stats.nacks_sent = rtcp_packet_type_counter_.nack_packets;
848 }
849
850 // Timestamps.
851 {
852 MutexLock lock(&ts_stats_lock_);
853 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
854 }
855
856 absl::optional<RtpRtcpInterface::SenderReportStats> rtcp_sr_stats =
857 rtp_rtcp_->GetSenderReportStats();
858 if (rtcp_sr_stats.has_value()) {
859 stats.last_sender_report_timestamp_ms =
860 rtcp_sr_stats->last_arrival_timestamp.ToMs() -
861 rtc::kNtpJan1970Millisecs;
862 stats.last_sender_report_remote_timestamp_ms =
863 rtcp_sr_stats->last_remote_timestamp.ToMs() - rtc::kNtpJan1970Millisecs;
864 stats.sender_reports_packets_sent = rtcp_sr_stats->packets_sent;
865 stats.sender_reports_bytes_sent = rtcp_sr_stats->bytes_sent;
866 stats.sender_reports_reports_count = rtcp_sr_stats->reports_count;
867 }
868
869 absl::optional<RtpRtcpInterface::NonSenderRttStats> non_sender_rtt_stats =
870 rtp_rtcp_->GetNonSenderRttStats();
871 if (non_sender_rtt_stats.has_value()) {
872 stats.round_trip_time = non_sender_rtt_stats->round_trip_time;
873 stats.round_trip_time_measurements =
874 non_sender_rtt_stats->round_trip_time_measurements;
875 stats.total_round_trip_time = non_sender_rtt_stats->total_round_trip_time;
876 }
877
878 return stats;
879 }
880
SetNACKStatus(bool enable,int max_packets)881 void ChannelReceive::SetNACKStatus(bool enable, int max_packets) {
882 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
883 // None of these functions can fail.
884 if (enable) {
885 rtp_receive_statistics_->SetMaxReorderingThreshold(max_packets);
886 acm_receiver_.EnableNack(max_packets);
887 } else {
888 rtp_receive_statistics_->SetMaxReorderingThreshold(
889 kDefaultMaxReorderingThreshold);
890 acm_receiver_.DisableNack();
891 }
892 }
893
SetNonSenderRttMeasurement(bool enabled)894 void ChannelReceive::SetNonSenderRttMeasurement(bool enabled) {
895 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
896 rtp_rtcp_->SetNonSenderRttMeasurement(enabled);
897 }
898
899 // Called when we are missing one or more packets.
ResendPackets(const uint16_t * sequence_numbers,int length)900 int ChannelReceive::ResendPackets(const uint16_t* sequence_numbers,
901 int length) {
902 return rtp_rtcp_->SendNACK(sequence_numbers, length);
903 }
904
RtcpPacketTypesCounterUpdated(uint32_t ssrc,const RtcpPacketTypeCounter & packet_counter)905 void ChannelReceive::RtcpPacketTypesCounterUpdated(
906 uint32_t ssrc,
907 const RtcpPacketTypeCounter& packet_counter) {
908 if (ssrc != remote_ssrc_) {
909 return;
910 }
911 MutexLock lock(&rtcp_counter_mutex_);
912 rtcp_packet_type_counter_ = packet_counter;
913 }
914
SetAssociatedSendChannel(const ChannelSendInterface * channel)915 void ChannelReceive::SetAssociatedSendChannel(
916 const ChannelSendInterface* channel) {
917 RTC_DCHECK_RUN_ON(&network_thread_checker_);
918 associated_send_channel_ = channel;
919 }
920
SetDepacketizerToDecoderFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)921 void ChannelReceive::SetDepacketizerToDecoderFrameTransformer(
922 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
923 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
924 // Depending on when the channel is created, the transformer might be set
925 // twice. Don't replace the delegate if it was already initialized.
926 if (!frame_transformer || frame_transformer_delegate_) {
927 RTC_DCHECK_NOTREACHED() << "Not setting the transformer?";
928 return;
929 }
930
931 InitFrameTransformerDelegate(std::move(frame_transformer));
932 }
933
SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)934 void ChannelReceive::SetFrameDecryptor(
935 rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
936 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
937 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
938 frame_decryptor_ = std::move(frame_decryptor);
939 }
940
OnLocalSsrcChange(uint32_t local_ssrc)941 void ChannelReceive::OnLocalSsrcChange(uint32_t local_ssrc) {
942 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
943 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
944 rtp_rtcp_->SetLocalSsrc(local_ssrc);
945 }
946
GetLocalSsrc() const947 uint32_t ChannelReceive::GetLocalSsrc() const {
948 // TODO(bugs.webrtc.org/11993): Expect to be called on the network thread.
949 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
950 return rtp_rtcp_->local_media_ssrc();
951 }
952
GetNetworkStatistics(bool get_and_clear_legacy_stats) const953 NetworkStatistics ChannelReceive::GetNetworkStatistics(
954 bool get_and_clear_legacy_stats) const {
955 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
956 NetworkStatistics stats;
957 acm_receiver_.GetNetworkStatistics(&stats, get_and_clear_legacy_stats);
958 return stats;
959 }
960
GetDecodingCallStatistics() const961 AudioDecodingCallStats ChannelReceive::GetDecodingCallStatistics() const {
962 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
963 AudioDecodingCallStats stats;
964 acm_receiver_.GetDecodingCallStatistics(&stats);
965 return stats;
966 }
967
GetDelayEstimate() const968 uint32_t ChannelReceive::GetDelayEstimate() const {
969 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
970 // Return the current jitter buffer delay + playout delay.
971 return acm_receiver_.FilteredCurrentDelayMs() + playout_delay_ms_;
972 }
973
SetMinimumPlayoutDelay(int delay_ms)974 bool ChannelReceive::SetMinimumPlayoutDelay(int delay_ms) {
975 // TODO(bugs.webrtc.org/11993): This should run on the network thread.
976 // We get here via RtpStreamsSynchronizer. Once that's done, many (all?) of
977 // these locks aren't needed.
978 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
979 // Limit to range accepted by both VoE and ACM, so we're at least getting as
980 // close as possible, instead of failing.
981 delay_ms = rtc::SafeClamp(delay_ms, kVoiceEngineMinMinPlayoutDelayMs,
982 kVoiceEngineMaxMinPlayoutDelayMs);
983 if (acm_receiver_.SetMinimumDelay(delay_ms) != 0) {
984 RTC_DLOG(LS_ERROR)
985 << "SetMinimumPlayoutDelay() failed to set min playout delay";
986 return false;
987 }
988 return true;
989 }
990
GetPlayoutRtpTimestamp(uint32_t * rtp_timestamp,int64_t * time_ms) const991 bool ChannelReceive::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
992 int64_t* time_ms) const {
993 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
994 if (!playout_timestamp_rtp_time_ms_)
995 return false;
996 *rtp_timestamp = playout_timestamp_rtp_;
997 *time_ms = playout_timestamp_rtp_time_ms_.value();
998 return true;
999 }
1000
SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,int64_t time_ms)1001 void ChannelReceive::SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,
1002 int64_t time_ms) {
1003 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1004 playout_timestamp_ntp_ = ntp_timestamp_ms;
1005 playout_timestamp_ntp_time_ms_ = time_ms;
1006 }
1007
1008 absl::optional<int64_t>
GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const1009 ChannelReceive::GetCurrentEstimatedPlayoutNtpTimestampMs(int64_t now_ms) const {
1010 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1011 if (!playout_timestamp_ntp_ || !playout_timestamp_ntp_time_ms_)
1012 return absl::nullopt;
1013
1014 int64_t elapsed_ms = now_ms - *playout_timestamp_ntp_time_ms_;
1015 return *playout_timestamp_ntp_ + elapsed_ms;
1016 }
1017
SetBaseMinimumPlayoutDelayMs(int delay_ms)1018 bool ChannelReceive::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
1019 return acm_receiver_.SetBaseMinimumDelayMs(delay_ms);
1020 }
1021
GetBaseMinimumPlayoutDelayMs() const1022 int ChannelReceive::GetBaseMinimumPlayoutDelayMs() const {
1023 return acm_receiver_.GetBaseMinimumDelayMs();
1024 }
1025
GetSyncInfo() const1026 absl::optional<Syncable::Info> ChannelReceive::GetSyncInfo() const {
1027 // TODO(bugs.webrtc.org/11993): This should run on the network thread.
1028 // We get here via RtpStreamsSynchronizer. Once that's done, many of
1029 // these locks aren't needed.
1030 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1031 Syncable::Info info;
1032 if (rtp_rtcp_->RemoteNTP(&info.capture_time_ntp_secs,
1033 &info.capture_time_ntp_frac,
1034 /*rtcp_arrival_time_secs=*/nullptr,
1035 /*rtcp_arrival_time_frac=*/nullptr,
1036 &info.capture_time_source_clock) != 0) {
1037 return absl::nullopt;
1038 }
1039
1040 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
1041 return absl::nullopt;
1042 }
1043 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
1044 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
1045
1046 int jitter_buffer_delay = acm_receiver_.FilteredCurrentDelayMs();
1047 info.current_delay_ms = jitter_buffer_delay + playout_delay_ms_;
1048
1049 return info;
1050 }
1051
UpdatePlayoutTimestamp(bool rtcp,int64_t now_ms)1052 void ChannelReceive::UpdatePlayoutTimestamp(bool rtcp, int64_t now_ms) {
1053 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1054 // TODO(bugs.webrtc.org/11993): Expect to be called exclusively on the
1055 // network thread. Once that's done, we won't need video_sync_lock_.
1056
1057 jitter_buffer_playout_timestamp_ = acm_receiver_.GetPlayoutTimestamp();
1058
1059 if (!jitter_buffer_playout_timestamp_) {
1060 // This can happen if this channel has not received any RTP packets. In
1061 // this case, NetEq is not capable of computing a playout timestamp.
1062 return;
1063 }
1064
1065 uint16_t delay_ms = 0;
1066 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
1067 RTC_DLOG(LS_WARNING)
1068 << "ChannelReceive::UpdatePlayoutTimestamp() failed to read"
1069 " playout delay from the ADM";
1070 return;
1071 }
1072
1073 RTC_DCHECK(jitter_buffer_playout_timestamp_);
1074 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
1075
1076 // Remove the playout delay.
1077 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
1078
1079 if (!rtcp && playout_timestamp != playout_timestamp_rtp_) {
1080 playout_timestamp_rtp_ = playout_timestamp;
1081 playout_timestamp_rtp_time_ms_ = now_ms;
1082 }
1083 playout_delay_ms_ = delay_ms;
1084 }
1085
GetRtpTimestampRateHz() const1086 int ChannelReceive::GetRtpTimestampRateHz() const {
1087 const auto decoder = acm_receiver_.LastDecoder();
1088 // Default to the playout frequency if we've not gotten any packets yet.
1089 // TODO(ossu): Zero clockrate can only happen if we've added an external
1090 // decoder for a format we don't support internally. Remove once that way of
1091 // adding decoders is gone!
1092 // TODO(kwiberg): `decoder->second.clockrate_hz` is an RTP clockrate as it
1093 // should, but `acm_receiver_.last_output_sample_rate_hz()` is a codec sample
1094 // rate, which is not always the same thing.
1095 return (decoder && decoder->second.clockrate_hz != 0)
1096 ? decoder->second.clockrate_hz
1097 : acm_receiver_.last_output_sample_rate_hz();
1098 }
1099
1100 } // namespace
1101
CreateChannelReceive(Clock * clock,NetEqFactory * neteq_factory,AudioDeviceModule * audio_device_module,Transport * rtcp_send_transport,RtcEventLog * rtc_event_log,uint32_t local_ssrc,uint32_t remote_ssrc,size_t jitter_buffer_max_packets,bool jitter_buffer_fast_playout,int jitter_buffer_min_delay_ms,bool enable_non_sender_rtt,rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,absl::optional<AudioCodecPairId> codec_pair_id,rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,const webrtc::CryptoOptions & crypto_options,rtc::scoped_refptr<FrameTransformerInterface> frame_transformer)1102 std::unique_ptr<ChannelReceiveInterface> CreateChannelReceive(
1103 Clock* clock,
1104 NetEqFactory* neteq_factory,
1105 AudioDeviceModule* audio_device_module,
1106 Transport* rtcp_send_transport,
1107 RtcEventLog* rtc_event_log,
1108 uint32_t local_ssrc,
1109 uint32_t remote_ssrc,
1110 size_t jitter_buffer_max_packets,
1111 bool jitter_buffer_fast_playout,
1112 int jitter_buffer_min_delay_ms,
1113 bool enable_non_sender_rtt,
1114 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
1115 absl::optional<AudioCodecPairId> codec_pair_id,
1116 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
1117 const webrtc::CryptoOptions& crypto_options,
1118 rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) {
1119 return std::make_unique<ChannelReceive>(
1120 clock, neteq_factory, audio_device_module, rtcp_send_transport,
1121 rtc_event_log, local_ssrc, remote_ssrc, jitter_buffer_max_packets,
1122 jitter_buffer_fast_playout, jitter_buffer_min_delay_ms,
1123 enable_non_sender_rtt, decoder_factory, codec_pair_id,
1124 std::move(frame_decryptor), crypto_options, std::move(frame_transformer));
1125 }
1126
1127 } // namespace voe
1128 } // namespace webrtc
1129