blob: ab2d48dff27e256489539039422237ccac40a729 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/delay_manager.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <stdio.h>
15#include <stdlib.h>
16#include <algorithm>
Ivo Creusen385b10b2017-10-13 12:37:27 +020017#include <numeric>
Yves Gerey988cc082018-10-23 12:03:01 +020018#include <string>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/audio_coding/neteq/delay_peak_detector.h"
Jakob Ivarssondb42ed22019-02-27 10:08:09 +010022#include "modules/audio_coding/neteq/histogram.h"
Jakob Ivarsson44507082019-03-05 16:59:03 +010023#include "modules/audio_coding/neteq/statistics_calculator.h"
Yves Gerey988cc082018-10-23 12:03:01 +020024#include "modules/include/module_common_types_public.h"
25#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010027#include "rtc_base/numerics/safe_conversions.h"
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010028#include "rtc_base/numerics/safe_minmax.h"
Ivo Creusen385b10b2017-10-13 12:37:27 +020029#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000030
Minyue Li002fbb82018-10-04 11:31:03 +020031namespace {
32
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010033constexpr int kLimitProbability = 1020054733; // 19/20 in Q30.
34constexpr int kLimitProbabilityStreaming = 1073204953; // 1999/2000 in Q30.
35constexpr int kMaxStreamingPeakPeriodMs = 600000; // 10 minutes in ms.
Minyue Li002fbb82018-10-04 11:31:03 +020036constexpr int kCumulativeSumDrift = 2; // Drift term for cumulative sum
37 // |iat_cumulative_sum_|.
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010038constexpr int kMinBaseMinimumDelayMs = 0;
39constexpr int kMaxBaseMinimumDelayMs = 10000;
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010040constexpr int kIatFactor = 32745; // 0.9993 in Q15.
41constexpr int kMaxIat = 64; // Max inter-arrival time to register.
Jakob Ivarssone98954c2019-02-06 15:37:50 +010042constexpr int kMaxReorderedPackets =
43 10; // Max number of consecutive reordered packets.
Jakob Ivarssondb42ed22019-02-27 10:08:09 +010044constexpr int kMaxHistoryPackets =
45 100; // Max number of packets used to calculate relative packet arrival
46 // delay.
47constexpr int kDelayBuckets = 100;
48constexpr int kBucketSizeMs = 20;
49
50int PercentileToQuantile(double percentile) {
51 return static_cast<int>((1 << 30) * percentile / 100.0 + 0.5);
52}
Minyue Li002fbb82018-10-04 11:31:03 +020053
54absl::optional<int> GetForcedLimitProbability() {
55 constexpr char kForceTargetDelayPercentileFieldTrial[] =
56 "WebRTC-Audio-NetEqForceTargetDelayPercentile";
57 const bool use_forced_target_delay_percentile =
58 webrtc::field_trial::IsEnabled(kForceTargetDelayPercentileFieldTrial);
59 if (use_forced_target_delay_percentile) {
60 const std::string field_trial_string = webrtc::field_trial::FindFullName(
61 kForceTargetDelayPercentileFieldTrial);
62 double percentile = -1.0;
63 if (sscanf(field_trial_string.c_str(), "Enabled-%lf", &percentile) == 1 &&
64 percentile >= 0.0 && percentile <= 100.0) {
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010065 return absl::make_optional<int>(
Jakob Ivarssondb42ed22019-02-27 10:08:09 +010066 PercentileToQuantile(percentile)); // in Q30.
Minyue Li002fbb82018-10-04 11:31:03 +020067 } else {
68 RTC_LOG(LS_WARNING) << "Invalid parameter for "
69 << kForceTargetDelayPercentileFieldTrial
70 << ", ignored.";
71 }
72 }
73 return absl::nullopt;
74}
75
Jakob Ivarssondb42ed22019-02-27 10:08:09 +010076struct DelayHistogramConfig {
77 int quantile = 1020054733; // 0.95 in Q30.
78 int forget_factor = 32745; // 0.9993 in Q15.
79};
80
81absl::optional<DelayHistogramConfig> GetDelayHistogramConfig() {
82 constexpr char kDelayHistogramFieldTrial[] =
83 "WebRTC-Audio-NetEqDelayHistogram";
84 const bool use_new_delay_manager =
85 webrtc::field_trial::IsEnabled(kDelayHistogramFieldTrial);
86 if (use_new_delay_manager) {
87 const auto field_trial_string =
88 webrtc::field_trial::FindFullName(kDelayHistogramFieldTrial);
89 DelayHistogramConfig config;
90 double percentile = -1.0;
91 double forget_factor = -1.0;
92 if (sscanf(field_trial_string.c_str(), "Enabled-%lf-%lf", &percentile,
93 &forget_factor) == 2 &&
94 percentile >= 0.0 && percentile <= 100.0 && forget_factor >= 0.0 &&
95 forget_factor <= 1.0) {
96 config.quantile = PercentileToQuantile(percentile);
97 config.forget_factor = (1 << 15) * forget_factor;
98 }
99 RTC_LOG(LS_INFO) << "Delay histogram config:"
100 << " quantile=" << config.quantile
101 << " forget_factor=" << config.forget_factor;
102 return absl::make_optional(config);
103 }
104 return absl::nullopt;
105}
106
Minyue Li002fbb82018-10-04 11:31:03 +0200107} // namespace
108
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109namespace webrtc {
110
Peter Kastingdce40cf2015-08-24 14:52:23 -0700111DelayManager::DelayManager(size_t max_packets_in_buffer,
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100112 int base_minimum_delay_ms,
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100113 int histogram_quantile,
114 HistogramMode histogram_mode,
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100115 bool enable_rtx_handling,
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700116 DelayPeakDetector* peak_detector,
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100117 const TickTimer* tick_timer,
Jakob Ivarsson44507082019-03-05 16:59:03 +0100118 StatisticsCalculator* statistics,
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100119 std::unique_ptr<Histogram> histogram)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120 : first_packet_received_(false),
121 max_packets_in_buffer_(max_packets_in_buffer),
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100122 histogram_(std::move(histogram)),
123 histogram_quantile_(histogram_quantile),
124 histogram_mode_(histogram_mode),
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700125 tick_timer_(tick_timer),
Jakob Ivarsson44507082019-03-05 16:59:03 +0100126 statistics_(statistics),
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100127 base_minimum_delay_ms_(base_minimum_delay_ms),
128 effective_minimum_delay_ms_(base_minimum_delay_ms),
Ivo Creusen385b10b2017-10-13 12:37:27 +0200129 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 target_level_(base_target_level_ << 8), // In Q8 domain.
131 packet_len_ms_(0),
132 streaming_mode_(false),
133 last_seq_no_(0),
134 last_timestamp_(0),
Ruslan Burakov76a74e62019-02-22 19:28:02 +0100135 minimum_delay_ms_(0),
Ruslan Burakovb35bacc2019-02-20 13:41:59 +0100136 maximum_delay_ms_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000137 iat_cumulative_sum_(0),
138 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000139 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +0200140 last_pack_cng_or_dtmf_(1),
141 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +0200142 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100143 enable_rtx_handling_(enable_rtx_handling) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000144 assert(peak_detector); // Should never be NULL.
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100145 RTC_CHECK(histogram_);
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100146 RTC_DCHECK_GE(base_minimum_delay_ms_, 0);
Minyue Li002fbb82018-10-04 11:31:03 +0200147
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000148 Reset();
149}
150
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100151std::unique_ptr<DelayManager> DelayManager::Create(
152 size_t max_packets_in_buffer,
153 int base_minimum_delay_ms,
154 bool enable_rtx_handling,
155 DelayPeakDetector* peak_detector,
Jakob Ivarsson44507082019-03-05 16:59:03 +0100156 const TickTimer* tick_timer,
157 StatisticsCalculator* statistics) {
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100158 int quantile;
159 std::unique_ptr<Histogram> histogram;
160 HistogramMode mode;
161 auto delay_histogram_config = GetDelayHistogramConfig();
162 if (delay_histogram_config) {
163 DelayHistogramConfig config = delay_histogram_config.value();
164 quantile = config.quantile;
165 histogram =
166 absl::make_unique<Histogram>(kDelayBuckets, config.forget_factor);
167 mode = RELATIVE_ARRIVAL_DELAY;
168 } else {
169 quantile = GetForcedLimitProbability().value_or(kLimitProbability);
170 histogram = absl::make_unique<Histogram>(kMaxIat + 1, kIatFactor);
171 mode = INTER_ARRIVAL_TIME;
172 }
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100173 return absl::make_unique<DelayManager>(
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100174 max_packets_in_buffer, base_minimum_delay_ms, quantile, mode,
Jakob Ivarsson44507082019-03-05 16:59:03 +0100175 enable_rtx_handling, peak_detector, tick_timer, statistics,
176 std::move(histogram));
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100177}
178
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000179DelayManager::~DelayManager() {}
180
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000181int DelayManager::Update(uint16_t sequence_number,
182 uint32_t timestamp,
183 int sample_rate_hz) {
184 if (sample_rate_hz <= 0) {
185 return -1;
186 }
187
188 if (!first_packet_received_) {
189 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700190 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000191 last_seq_no_ = sequence_number;
192 last_timestamp_ = timestamp;
193 first_packet_received_ = true;
194 return 0;
195 }
196
197 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000198 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000199 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
200 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 // Wrong timestamp or sequence order; use stored value.
202 packet_len_ms = packet_len_ms_;
203 } else {
204 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800205 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000206 static_cast<uint32_t>(timestamp - last_timestamp_) /
207 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800208 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700209 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 }
211
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100212 bool reordered = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000213 if (packet_len_ms > 0) {
214 // Cannot update statistics unless |packet_len_ms| is valid.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 if (streaming_mode_) {
216 UpdateCumulativeSums(packet_len_ms, sequence_number);
217 }
218
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100219 // Inter-arrival time (IAT) in integer "packet times" (rounding down). This
220 // is the value added to the inter-arrival time histogram.
221 int iat_ms = packet_iat_stopwatch_->ElapsedMs();
222 int iat_packets = iat_ms / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000224 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000225 // Compensate for gap in the sequence numbers. Reduce IAT with the
226 // expected extra time due to lost packets, but ensure that the IAT is
227 // not negative.
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100228 int packet_offset =
229 static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
230 iat_packets -= packet_offset;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000231 iat_packets = std::max(iat_packets, 0);
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100232 iat_ms -= packet_offset * packet_len_ms;
233 iat_ms = std::max(iat_ms, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000234 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100235 int packet_offset =
236 static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
237 iat_packets += packet_offset;
238 iat_ms += packet_offset * packet_len_ms;
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100239 reordered = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000240 }
241
Jakob Ivarsson44507082019-03-05 16:59:03 +0100242 int iat_delay = iat_ms - packet_len_ms;
243 int relative_delay;
244 if (reordered) {
245 relative_delay = std::max(iat_delay, 0);
246 } else {
247 UpdateDelayHistory(iat_delay);
248 relative_delay = CalculateRelativePacketArrivalDelay();
249 }
250 statistics_->RelativePacketArrivalDelay(relative_delay);
251
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100252 switch (histogram_mode_) {
253 case RELATIVE_ARRIVAL_DELAY: {
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100254 const int index = relative_delay / kBucketSizeMs;
255 if (index < histogram_->NumBuckets()) {
256 // Maximum delay to register is 2000 ms.
257 histogram_->Add(index);
258 }
259 break;
260 }
261 case INTER_ARRIVAL_TIME: {
262 // Saturate IAT at maximum value.
263 iat_packets = std::min(iat_packets, histogram_->NumBuckets() - 1);
264 histogram_->Add(iat_packets);
265 break;
266 }
267 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000268 // Calculate new |target_level_| based on updated statistics.
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100269 target_level_ = CalculateTargetLevel(iat_packets, reordered);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000270 if (streaming_mode_) {
271 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
272 }
273
274 LimitTargetLevel();
275 } // End if (packet_len_ms > 0).
276
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100277 if (enable_rtx_handling_ && reordered &&
278 num_reordered_packets_ < kMaxReorderedPackets) {
279 ++num_reordered_packets_;
280 return 0;
281 }
282 num_reordered_packets_ = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700284 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000285 last_seq_no_ = sequence_number;
286 last_timestamp_ = timestamp;
287 return 0;
288}
289
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100290void DelayManager::UpdateDelayHistory(int iat_delay) {
291 delay_history_.push_back(iat_delay);
292 if (delay_history_.size() > kMaxHistoryPackets) {
293 delay_history_.pop_front();
294 }
295}
296
297int DelayManager::CalculateRelativePacketArrivalDelay() const {
298 // This effectively calculates arrival delay of a packet relative to the
299 // packet preceding the history window. If the arrival delay ever becomes
300 // smaller than zero, it means the reference packet is invalid, and we
301 // move the reference.
302 int relative_delay = 0;
303 for (int delay : delay_history_) {
304 relative_delay += delay;
305 relative_delay = std::max(relative_delay, 0);
306 }
307 return relative_delay;
308}
309
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310void DelayManager::UpdateCumulativeSums(int packet_len_ms,
311 uint16_t sequence_number) {
312 // Calculate IAT in Q8, including fractions of a packet (i.e., more
313 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700314 int iat_packets_q8 =
315 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 // Calculate cumulative sum IAT with sequence number compensation. The sum
317 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200318 iat_cumulative_sum_ +=
319 (iat_packets_q8 -
320 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321 // Subtract drift term.
322 iat_cumulative_sum_ -= kCumulativeSumDrift;
323 // Ensure not negative.
324 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
325 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
326 // Found a new maximum.
327 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700328 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700330 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 // Too long since the last maximum was observed; decrease max value.
332 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
333 }
334}
335
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000336// Enforces upper and lower limits for |target_level_|. The upper limit is
337// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
338// headroom for natural fluctuations around the target, and ii) equivalent of
339// |maximum_delay_ms_| in packets. Note that in practice, if no
340// |maximum_delay_ms_| is specified, this does not have any impact, since the
341// target level is far below the buffer capacity in all reasonable cases.
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100342// The lower limit is equivalent of |effective_minimum_delay_ms_| in packets.
343// We update |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000344// TODO(hlundin): Move this check to the buffer logistics class.
345void DelayManager::LimitTargetLevel() {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100346 if (packet_len_ms_ > 0 && effective_minimum_delay_ms_ > 0) {
347 int minimum_delay_packet_q8 =
348 (effective_minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000349 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000351
352 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
353 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
354 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
355 }
356
357 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700358 int max_buffer_packets_q8 =
359 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000360 target_level_ = std::min(target_level_, max_buffer_packets_q8);
361
362 // Sanity check, at least 1 packet (in Q8).
363 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364}
365
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100366int DelayManager::CalculateTargetLevel(int iat_packets, bool reordered) {
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100367 int limit_probability = histogram_quantile_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368 if (streaming_mode_) {
369 limit_probability = kLimitProbabilityStreaming;
370 }
371
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100372 int bucket_index = histogram_->Quantile(limit_probability);
373 int target_level;
374 switch (histogram_mode_) {
375 case RELATIVE_ARRIVAL_DELAY: {
376 target_level = 1 + bucket_index * kBucketSizeMs / packet_len_ms_;
377 base_target_level_ = target_level;
378 break;
379 }
380 case INTER_ARRIVAL_TIME: {
381 target_level = bucket_index;
382 base_target_level_ = target_level;
383 // Update detector for delay peaks.
384 bool delay_peak_found =
385 peak_detector_.Update(iat_packets, reordered, target_level);
386 if (delay_peak_found) {
387 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
388 }
389 break;
390 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 }
392
393 // Sanity check. |target_level| must be strictly positive.
394 target_level = std::max(target_level, 1);
395 // Scale to Q8 and assign to member variable.
396 target_level_ = target_level << 8;
397 return target_level_;
398}
399
400int DelayManager::SetPacketAudioLength(int length_ms) {
401 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100402 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000403 return -1;
404 }
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100405 if (histogram_mode_ == INTER_ARRIVAL_TIME &&
406 frame_length_change_experiment_ && packet_len_ms_ != length_ms &&
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100407 packet_len_ms_ > 0) {
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100408 histogram_->Scale(packet_len_ms_, length_ms);
Ivo Creusen385b10b2017-10-13 12:37:27 +0200409 }
410
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 packet_len_ms_ = length_ms;
412 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700413 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000414 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
415 return 0;
416}
417
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418void DelayManager::Reset() {
419 packet_len_ms_ = 0; // Packet size unknown.
420 streaming_mode_ = false;
421 peak_detector_.Reset();
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100422 histogram_->Reset();
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100423 base_target_level_ = 4;
424 target_level_ = base_target_level_ << 8;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700425 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
426 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427 iat_cumulative_sum_ = 0;
428 max_iat_cumulative_sum_ = 0;
429 last_pack_cng_or_dtmf_ = 1;
430}
431
henrik.lundin0d838572016-10-13 03:35:55 -0700432double DelayManager::EstimatedClockDriftPpm() const {
433 double sum = 0.0;
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100434 // Calculate the expected value based on the probabilities in
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100435 // |histogram_|.
436 auto buckets = histogram_->buckets();
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100437 for (size_t i = 0; i < buckets.size(); ++i) {
438 sum += static_cast<double>(buckets[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439 }
Jakob Ivarssondb42ed22019-02-27 10:08:09 +0100440 // The probabilities in |histogram_| are in Q30. Divide by 1 << 30 to
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100441 // convert to Q0; subtract the nominal inter-arrival time (1) to make a zero
henrik.lundin0d838572016-10-13 03:35:55 -0700442 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
443 // (ppm).
444 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000445}
446
447bool DelayManager::PeakFound() const {
448 return peak_detector_.peak_found();
449}
450
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700451void DelayManager::ResetPacketIatCount() {
452 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000453}
454
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000455// Note that |low_limit| and |higher_limit| are not assigned to
456// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
457// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000458void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
459 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100460 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461 assert(false);
462 return;
463 }
464
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
466 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000467 window_20ms = (20 << 8) / packet_len_ms_;
468 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000469
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000471 *lower_limit = (target_level_ * 3) / 4;
472 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000473 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000474 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000475}
476
477int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000478 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479}
480
ossuf1b08da2016-09-23 02:19:43 -0700481void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
482 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 last_pack_cng_or_dtmf_ = 1;
484 } else if (last_pack_cng_or_dtmf_ != 0) {
485 last_pack_cng_or_dtmf_ = -1;
486 }
487}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000488
henrik.lundinb8c55b12017-05-10 07:38:01 -0700489void DelayManager::RegisterEmptyPacket() {
490 ++last_seq_no_;
491}
492
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100493bool DelayManager::IsValidMinimumDelay(int delay_ms) const {
494 return 0 <= delay_ms && delay_ms <= MinimumDelayUpperBound();
495}
496
497bool DelayManager::IsValidBaseMinimumDelay(int delay_ms) const {
498 return kMinBaseMinimumDelayMs <= delay_ms &&
499 delay_ms <= kMaxBaseMinimumDelayMs;
Ruslan Burakovedbea462019-02-04 16:17:31 +0100500}
501
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000502bool DelayManager::SetMinimumDelay(int delay_ms) {
Ruslan Burakovedbea462019-02-04 16:17:31 +0100503 if (!IsValidMinimumDelay(delay_ms)) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000504 return false;
505 }
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100506
507 minimum_delay_ms_ = delay_ms;
508 UpdateEffectiveMinimumDelay();
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000509 return true;
510}
511
512bool DelayManager::SetMaximumDelay(int delay_ms) {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100513 // If |delay_ms| is zero then it unsets the maximum delay and target level is
514 // unconstrained by maximum delay.
515 if (delay_ms != 0 &&
516 (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_)) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000517 // Maximum delay shouldn't be less than minimum delay or less than a packet.
518 return false;
519 }
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100520
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000521 maximum_delay_ms_ = delay_ms;
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100522 UpdateEffectiveMinimumDelay();
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000523 return true;
524}
525
Ruslan Burakovedbea462019-02-04 16:17:31 +0100526bool DelayManager::SetBaseMinimumDelay(int delay_ms) {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100527 if (!IsValidBaseMinimumDelay(delay_ms)) {
Ruslan Burakovedbea462019-02-04 16:17:31 +0100528 return false;
529 }
530
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100531 base_minimum_delay_ms_ = delay_ms;
532 UpdateEffectiveMinimumDelay();
Ruslan Burakovedbea462019-02-04 16:17:31 +0100533 return true;
534}
535
536int DelayManager::GetBaseMinimumDelay() const {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100537 return base_minimum_delay_ms_;
Ruslan Burakovedbea462019-02-04 16:17:31 +0100538}
539
Yves Gerey665174f2018-06-19 15:03:05 +0200540int DelayManager::base_target_level() const {
541 return base_target_level_;
542}
543void DelayManager::set_streaming_mode(bool value) {
544 streaming_mode_ = value;
545}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000546int DelayManager::last_pack_cng_or_dtmf() const {
547 return last_pack_cng_or_dtmf_;
548}
549
550void DelayManager::set_last_pack_cng_or_dtmf(int value) {
551 last_pack_cng_or_dtmf_ = value;
552}
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100553
554void DelayManager::UpdateEffectiveMinimumDelay() {
555 // Clamp |base_minimum_delay_ms_| into the range which can be effectively
556 // used.
557 const int base_minimum_delay_ms =
558 rtc::SafeClamp(base_minimum_delay_ms_, 0, MinimumDelayUpperBound());
559 effective_minimum_delay_ms_ =
560 std::max(minimum_delay_ms_, base_minimum_delay_ms);
561}
562
563int DelayManager::MinimumDelayUpperBound() const {
564 // Choose the lowest possible bound discarding 0 cases which mean the value
565 // is not set and unconstrained.
566 int q75 = MaxBufferTimeQ75();
567 q75 = q75 > 0 ? q75 : kMaxBaseMinimumDelayMs;
568 const int maximum_delay_ms =
569 maximum_delay_ms_ > 0 ? maximum_delay_ms_ : kMaxBaseMinimumDelayMs;
570 return std::min(maximum_delay_ms, q75);
571}
572
573int DelayManager::MaxBufferTimeQ75() const {
574 const int max_buffer_time = max_packets_in_buffer_ * packet_len_ms_;
575 return rtc::dchecked_cast<int>(3 * max_buffer_time / 4);
576}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000577} // namespace webrtc