blob: d2dd85dacbe68d8020e8ef784daecbf5dcbcc048 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "modules/audio_coding/neteq/delay_peak_detector.h"
Yves Gerey988cc082018-10-23 12:03:01 +020021#include "modules/include/module_common_types_public.h"
22#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010024#include "rtc_base/numerics/safe_conversions.h"
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010025#include "rtc_base/numerics/safe_minmax.h"
Ivo Creusen385b10b2017-10-13 12:37:27 +020026#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000027
Minyue Li002fbb82018-10-04 11:31:03 +020028namespace {
29
30constexpr int kLimitProbability = 53687091; // 1/20 in Q30.
31constexpr int kLimitProbabilityStreaming = 536871; // 1/2000 in Q30.
32constexpr int kMaxStreamingPeakPeriodMs = 600000; // 10 minutes in ms.
33constexpr int kCumulativeSumDrift = 2; // Drift term for cumulative sum
34 // |iat_cumulative_sum_|.
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010035constexpr int kMinBaseMinimumDelayMs = 0;
36constexpr int kMaxBaseMinimumDelayMs = 10000;
Minyue Li002fbb82018-10-04 11:31:03 +020037// Steady-state forgetting factor for |iat_vector_|, 0.9993 in Q15.
38constexpr int kIatFactor_ = 32745;
39constexpr int kMaxIat = 64; // Max inter-arrival time to register.
Jakob Ivarssone98954c2019-02-06 15:37:50 +010040constexpr int kMaxReorderedPackets =
41 10; // Max number of consecutive reordered packets.
Minyue Li002fbb82018-10-04 11:31:03 +020042
43absl::optional<int> GetForcedLimitProbability() {
44 constexpr char kForceTargetDelayPercentileFieldTrial[] =
45 "WebRTC-Audio-NetEqForceTargetDelayPercentile";
46 const bool use_forced_target_delay_percentile =
47 webrtc::field_trial::IsEnabled(kForceTargetDelayPercentileFieldTrial);
48 if (use_forced_target_delay_percentile) {
49 const std::string field_trial_string = webrtc::field_trial::FindFullName(
50 kForceTargetDelayPercentileFieldTrial);
51 double percentile = -1.0;
52 if (sscanf(field_trial_string.c_str(), "Enabled-%lf", &percentile) == 1 &&
53 percentile >= 0.0 && percentile <= 100.0) {
54 return absl::make_optional<int>(static_cast<int>(
55 (1 << 30) * (100.0 - percentile) / 100.0 + 0.5)); // in Q30.
56 } else {
57 RTC_LOG(LS_WARNING) << "Invalid parameter for "
58 << kForceTargetDelayPercentileFieldTrial
59 << ", ignored.";
60 }
61 }
62 return absl::nullopt;
63}
64
65} // namespace
66
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000067namespace webrtc {
68
Peter Kastingdce40cf2015-08-24 14:52:23 -070069DelayManager::DelayManager(size_t max_packets_in_buffer,
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010070 int base_minimum_delay_ms,
Jakob Ivarssone98954c2019-02-06 15:37:50 +010071 bool enable_rtx_handling,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070072 DelayPeakDetector* peak_detector,
73 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000074 : first_packet_received_(false),
75 max_packets_in_buffer_(max_packets_in_buffer),
76 iat_vector_(kMaxIat + 1, 0),
77 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070078 tick_timer_(tick_timer),
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010079 base_minimum_delay_ms_(base_minimum_delay_ms),
80 effective_minimum_delay_ms_(base_minimum_delay_ms),
Ivo Creusen385b10b2017-10-13 12:37:27 +020081 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 target_level_(base_target_level_ << 8), // In Q8 domain.
83 packet_len_ms_(0),
84 streaming_mode_(false),
85 last_seq_no_(0),
86 last_timestamp_(0),
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010087 minimum_delay_ms_(base_minimum_delay_ms_),
Ruslan Burakovb35bacc2019-02-20 13:41:59 +010088 maximum_delay_ms_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 iat_cumulative_sum_(0),
90 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020092 last_pack_cng_or_dtmf_(1),
93 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +020094 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
Jakob Ivarssone98954c2019-02-06 15:37:50 +010095 forced_limit_probability_(GetForcedLimitProbability()),
96 enable_rtx_handling_(enable_rtx_handling) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 assert(peak_detector); // Should never be NULL.
Ruslan Burakov4a68fb92019-02-13 14:25:39 +010098 RTC_DCHECK_GE(base_minimum_delay_ms_, 0);
Minyue Li002fbb82018-10-04 11:31:03 +020099
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 Reset();
101}
102
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000103DelayManager::~DelayManager() {}
104
105const DelayManager::IATVector& DelayManager::iat_vector() const {
106 return iat_vector_;
107}
108
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109// Set the histogram vector to an exponentially decaying distribution
110// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
111// iat_vector_ is in Q30.
112void DelayManager::ResetHistogram() {
113 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
114 // of iat_vector_ is 1.
115 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
116 IATVector::iterator it = iat_vector_.begin();
117 for (; it < iat_vector_.end(); it++) {
118 temp_prob >>= 1;
119 (*it) = temp_prob << 16;
120 }
121 base_target_level_ = 4;
122 target_level_ = base_target_level_ << 8;
123}
124
125int DelayManager::Update(uint16_t sequence_number,
126 uint32_t timestamp,
127 int sample_rate_hz) {
128 if (sample_rate_hz <= 0) {
129 return -1;
130 }
131
132 if (!first_packet_received_) {
133 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700134 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135 last_seq_no_ = sequence_number;
136 last_timestamp_ = timestamp;
137 first_packet_received_ = true;
138 return 0;
139 }
140
141 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000142 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000143 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
144 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000145 // Wrong timestamp or sequence order; use stored value.
146 packet_len_ms = packet_len_ms_;
147 } else {
148 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800149 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150 static_cast<uint32_t>(timestamp - last_timestamp_) /
151 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800152 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700153 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000154 }
155
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100156 bool reordered = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 if (packet_len_ms > 0) {
158 // Cannot update statistics unless |packet_len_ms| is valid.
159 // Calculate inter-arrival time (IAT) in integer "packet times"
160 // (rounding down). This is the value used as index to the histogram
161 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700162 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000163
164 if (streaming_mode_) {
165 UpdateCumulativeSums(packet_len_ms, sequence_number);
166 }
167
168 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000169 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000170 // Compensate for gap in the sequence numbers. Reduce IAT with the
171 // expected extra time due to lost packets, but ensure that the IAT is
172 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000173 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000174 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000175 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
176 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100177 reordered = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000178 }
179
180 // Saturate IAT at maximum value.
181 const int max_iat = kMaxIat;
182 iat_packets = std::min(iat_packets, max_iat);
183 UpdateHistogram(iat_packets);
184 // Calculate new |target_level_| based on updated statistics.
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100185 target_level_ = CalculateTargetLevel(iat_packets, reordered);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000186 if (streaming_mode_) {
187 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
188 }
189
190 LimitTargetLevel();
191 } // End if (packet_len_ms > 0).
192
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100193 if (enable_rtx_handling_ && reordered &&
194 num_reordered_packets_ < kMaxReorderedPackets) {
195 ++num_reordered_packets_;
196 return 0;
197 }
198 num_reordered_packets_ = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000199 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700200 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 last_seq_no_ = sequence_number;
202 last_timestamp_ = timestamp;
203 return 0;
204}
205
206void DelayManager::UpdateCumulativeSums(int packet_len_ms,
207 uint16_t sequence_number) {
208 // Calculate IAT in Q8, including fractions of a packet (i.e., more
209 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700210 int iat_packets_q8 =
211 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 // Calculate cumulative sum IAT with sequence number compensation. The sum
213 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200214 iat_cumulative_sum_ +=
215 (iat_packets_q8 -
216 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 // Subtract drift term.
218 iat_cumulative_sum_ -= kCumulativeSumDrift;
219 // Ensure not negative.
220 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
221 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
222 // Found a new maximum.
223 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700224 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000225 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700226 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000227 // Too long since the last maximum was observed; decrease max value.
228 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
229 }
230}
231
232// Each element in the vector is first multiplied by the forgetting factor
233// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
234// increased (additive) by 1 - |iat_factor_|. This way, the probability of
235// |iat_packets| is slightly increased, while the sum of the histogram remains
236// constant (=1).
237// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
238// longer sum up to 1 (in Q30) after the update. To correct this, a correction
239// term is added or subtracted from the first element (or elements) of the
240// vector.
241// The forgetting factor |iat_factor_| is also updated. When the DelayManager
242// is reset, the factor is set to 0 to facilitate rapid convergence in the
243// beginning. With each update of the histogram, the factor is increased towards
244// the steady-state value |kIatFactor_|.
245void DelayManager::UpdateHistogram(size_t iat_packets) {
246 assert(iat_packets < iat_vector_.size());
247 int vector_sum = 0; // Sum up the vector elements as they are processed.
248 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200249 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
250 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000251 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
252 vector_sum += *it;
253 }
254
255 // Increase the probability for the currently observed inter-arrival time
256 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
257 // Thus, left-shift 15 steps to obtain result in Q30.
258 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
259 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
260
261 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
262 // fixed-point rounding errors.
263 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
264 if (vector_sum != 0) {
265 // Modify a few values early in |iat_vector_|.
266 int flip_sign = vector_sum > 0 ? -1 : 1;
267 IATVector::iterator it = iat_vector_.begin();
268 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
269 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
270 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
271 *it += correction;
272 vector_sum += correction;
273 ++it;
274 }
275 }
276 assert(vector_sum == 0); // Verify that the above is correct.
277
278 // Update |iat_factor_| (changes only during the first seconds after a reset).
279 // The factor converges to |kIatFactor_|.
280 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
281}
282
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000283// Enforces upper and lower limits for |target_level_|. The upper limit is
284// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
285// headroom for natural fluctuations around the target, and ii) equivalent of
286// |maximum_delay_ms_| in packets. Note that in practice, if no
287// |maximum_delay_ms_| is specified, this does not have any impact, since the
288// target level is far below the buffer capacity in all reasonable cases.
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100289// The lower limit is equivalent of |effective_minimum_delay_ms_| in packets.
290// We update |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291// TODO(hlundin): Move this check to the buffer logistics class.
292void DelayManager::LimitTargetLevel() {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100293 if (packet_len_ms_ > 0 && effective_minimum_delay_ms_ > 0) {
294 int minimum_delay_packet_q8 =
295 (effective_minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000296 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298
299 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
300 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
301 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
302 }
303
304 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700305 int max_buffer_packets_q8 =
306 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000307 target_level_ = std::min(target_level_, max_buffer_packets_q8);
308
309 // Sanity check, at least 1 packet (in Q8).
310 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311}
312
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100313int DelayManager::CalculateTargetLevel(int iat_packets, bool reordered) {
Minyue Li002fbb82018-10-04 11:31:03 +0200314 int limit_probability = forced_limit_probability_.value_or(kLimitProbability);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 if (streaming_mode_) {
316 limit_probability = kLimitProbabilityStreaming;
317 }
318
319 // Calculate target buffer level from inter-arrival time histogram.
320 // Find the |iat_index| for which the probability of observing an
321 // inter-arrival time larger than or equal to |iat_index| is less than or
322 // equal to |limit_probability|. The sought probability is estimated using
323 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
324 // the end up until |iat_index|. Now, since the sum of all elements is 1
325 // (in Q30) by definition, and since the solution is often a low value for
326 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
327 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200328 size_t index = 0; // Start from the beginning of |iat_vector_|.
329 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
331
332 do {
333 // Subtract the probabilities one by one until the sum is no longer greater
334 // than limit_probability.
335 ++index;
336 sum -= iat_vector_[index];
337 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
338
339 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000340 int target_level = static_cast<int>(index);
341 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000342
343 // Update detector for delay peaks.
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100344 bool delay_peak_found =
345 peak_detector_.Update(iat_packets, reordered, target_level);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000347 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000348 }
349
350 // Sanity check. |target_level| must be strictly positive.
351 target_level = std::max(target_level, 1);
352 // Scale to Q8 and assign to member variable.
353 target_level_ = target_level << 8;
354 return target_level_;
355}
356
357int DelayManager::SetPacketAudioLength(int length_ms) {
358 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360 return -1;
361 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200362 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
363 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
364 }
365
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 packet_len_ms_ = length_ms;
367 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700368 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
370 return 0;
371}
372
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373void DelayManager::Reset() {
374 packet_len_ms_ = 0; // Packet size unknown.
375 streaming_mode_ = false;
376 peak_detector_.Reset();
377 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200378 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700379 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
380 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381 iat_cumulative_sum_ = 0;
382 max_iat_cumulative_sum_ = 0;
383 last_pack_cng_or_dtmf_ = 1;
384}
385
henrik.lundin0d838572016-10-13 03:35:55 -0700386double DelayManager::EstimatedClockDriftPpm() const {
387 double sum = 0.0;
388 // Calculate the expected value based on the probabilities in |iat_vector_|.
389 for (size_t i = 0; i < iat_vector_.size(); ++i) {
390 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 }
henrik.lundin0d838572016-10-13 03:35:55 -0700392 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
393 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
394 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
395 // (ppm).
396 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397}
398
399bool DelayManager::PeakFound() const {
400 return peak_detector_.peak_found();
401}
402
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700403void DelayManager::ResetPacketIatCount() {
404 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405}
406
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000407// Note that |low_limit| and |higher_limit| are not assigned to
408// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
409// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000410void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
411 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100412 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413 assert(false);
414 return;
415 }
416
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
418 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000419 window_20ms = (20 << 8) / packet_len_ms_;
420 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000421
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000422 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000423 *lower_limit = (target_level_ * 3) / 4;
424 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000425 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000426 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427}
428
429int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000430 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000431}
432
ossuf1b08da2016-09-23 02:19:43 -0700433void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
434 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 last_pack_cng_or_dtmf_ = 1;
436 } else if (last_pack_cng_or_dtmf_ != 0) {
437 last_pack_cng_or_dtmf_ = -1;
438 }
439}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000440
henrik.lundinb8c55b12017-05-10 07:38:01 -0700441void DelayManager::RegisterEmptyPacket() {
442 ++last_seq_no_;
443}
444
Ivo Creusen385b10b2017-10-13 12:37:27 +0200445DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
446 int old_packet_length,
447 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200448 if (old_packet_length == 0) {
449 // If we don't know the previous frame length, don't make any changes to the
450 // histogram.
451 return histogram;
452 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200453 RTC_DCHECK_GT(new_packet_length, 0);
454 RTC_DCHECK_EQ(old_packet_length % 10, 0);
455 RTC_DCHECK_EQ(new_packet_length % 10, 0);
456 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100457 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200458 int time_counter = 0;
459 size_t new_histogram_idx = 0;
460 for (size_t i = 0; i < histogram.size(); i++) {
461 acc += histogram[i];
462 time_counter += old_packet_length;
463 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100464 const int64_t scaled_acc = acc * new_packet_length / time_counter;
465 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200466 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100467 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
468 new_histogram[new_histogram_idx] =
469 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
470 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200471 new_histogram_idx =
472 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
473 time_counter -= new_packet_length;
474 }
475 // Only subtract the part that was succesfully written to the new histogram.
476 acc -= actually_used_acc;
477 }
478 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100479 // last bin. If we cannot add everything to the last bin we need to add as
480 // much as possible to the bins after the last bin (this is only possible
481 // when compressing a histogram).
482 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
483 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
484 new_histogram[new_histogram_idx] =
485 rtc::saturated_cast<int>(old_histogram_val + acc);
486 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
487 new_histogram_idx++;
488 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200489 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100490 if (acc == 0) {
491 // If acc is non-zero, we were not able to add everything to the new
492 // histogram, so this check will not hold.
493 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
494 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
495 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200496 return new_histogram;
497}
498
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100499bool DelayManager::IsValidMinimumDelay(int delay_ms) const {
500 return 0 <= delay_ms && delay_ms <= MinimumDelayUpperBound();
501}
502
503bool DelayManager::IsValidBaseMinimumDelay(int delay_ms) const {
504 return kMinBaseMinimumDelayMs <= delay_ms &&
505 delay_ms <= kMaxBaseMinimumDelayMs;
Ruslan Burakovedbea462019-02-04 16:17:31 +0100506}
507
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000508bool DelayManager::SetMinimumDelay(int delay_ms) {
Ruslan Burakovedbea462019-02-04 16:17:31 +0100509 if (!IsValidMinimumDelay(delay_ms)) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000510 return false;
511 }
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100512
513 minimum_delay_ms_ = delay_ms;
514 UpdateEffectiveMinimumDelay();
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000515 return true;
516}
517
518bool DelayManager::SetMaximumDelay(int delay_ms) {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100519 // If |delay_ms| is zero then it unsets the maximum delay and target level is
520 // unconstrained by maximum delay.
521 if (delay_ms != 0 &&
522 (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_)) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000523 // Maximum delay shouldn't be less than minimum delay or less than a packet.
524 return false;
525 }
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100526
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000527 maximum_delay_ms_ = delay_ms;
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100528 UpdateEffectiveMinimumDelay();
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000529 return true;
530}
531
Ruslan Burakovedbea462019-02-04 16:17:31 +0100532bool DelayManager::SetBaseMinimumDelay(int delay_ms) {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100533 if (!IsValidBaseMinimumDelay(delay_ms)) {
Ruslan Burakovedbea462019-02-04 16:17:31 +0100534 return false;
535 }
536
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100537 base_minimum_delay_ms_ = delay_ms;
538 UpdateEffectiveMinimumDelay();
Ruslan Burakovedbea462019-02-04 16:17:31 +0100539 return true;
540}
541
542int DelayManager::GetBaseMinimumDelay() const {
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100543 return base_minimum_delay_ms_;
Ruslan Burakovedbea462019-02-04 16:17:31 +0100544}
545
Yves Gerey665174f2018-06-19 15:03:05 +0200546int DelayManager::base_target_level() const {
547 return base_target_level_;
548}
549void DelayManager::set_streaming_mode(bool value) {
550 streaming_mode_ = value;
551}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000552int DelayManager::last_pack_cng_or_dtmf() const {
553 return last_pack_cng_or_dtmf_;
554}
555
556void DelayManager::set_last_pack_cng_or_dtmf(int value) {
557 last_pack_cng_or_dtmf_ = value;
558}
Ruslan Burakov4a68fb92019-02-13 14:25:39 +0100559
560void DelayManager::UpdateEffectiveMinimumDelay() {
561 // Clamp |base_minimum_delay_ms_| into the range which can be effectively
562 // used.
563 const int base_minimum_delay_ms =
564 rtc::SafeClamp(base_minimum_delay_ms_, 0, MinimumDelayUpperBound());
565 effective_minimum_delay_ms_ =
566 std::max(minimum_delay_ms_, base_minimum_delay_ms);
567}
568
569int DelayManager::MinimumDelayUpperBound() const {
570 // Choose the lowest possible bound discarding 0 cases which mean the value
571 // is not set and unconstrained.
572 int q75 = MaxBufferTimeQ75();
573 q75 = q75 > 0 ? q75 : kMaxBaseMinimumDelayMs;
574 const int maximum_delay_ms =
575 maximum_delay_ms_ > 0 ? maximum_delay_ms_ : kMaxBaseMinimumDelayMs;
576 return std::min(maximum_delay_ms, q75);
577}
578
579int DelayManager::MaxBufferTimeQ75() const {
580 const int max_buffer_time = max_packets_in_buffer_ * packet_len_ms_;
581 return rtc::dchecked_cast<int>(3 * max_buffer_time / 4);
582}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583} // namespace webrtc