blob: c97d5356d4c93ae3c2fc6a999319481280440655 [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"
Ivo Creusen385b10b2017-10-13 12:37:27 +020025#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000026
Minyue Li002fbb82018-10-04 11:31:03 +020027namespace {
28
29constexpr int kLimitProbability = 53687091; // 1/20 in Q30.
30constexpr int kLimitProbabilityStreaming = 536871; // 1/2000 in Q30.
31constexpr int kMaxStreamingPeakPeriodMs = 600000; // 10 minutes in ms.
32constexpr int kCumulativeSumDrift = 2; // Drift term for cumulative sum
33 // |iat_cumulative_sum_|.
34// Steady-state forgetting factor for |iat_vector_|, 0.9993 in Q15.
35constexpr int kIatFactor_ = 32745;
36constexpr int kMaxIat = 64; // Max inter-arrival time to register.
Jakob Ivarssone98954c2019-02-06 15:37:50 +010037constexpr int kMaxReorderedPackets =
38 10; // Max number of consecutive reordered packets.
Minyue Li002fbb82018-10-04 11:31:03 +020039
40absl::optional<int> GetForcedLimitProbability() {
41 constexpr char kForceTargetDelayPercentileFieldTrial[] =
42 "WebRTC-Audio-NetEqForceTargetDelayPercentile";
43 const bool use_forced_target_delay_percentile =
44 webrtc::field_trial::IsEnabled(kForceTargetDelayPercentileFieldTrial);
45 if (use_forced_target_delay_percentile) {
46 const std::string field_trial_string = webrtc::field_trial::FindFullName(
47 kForceTargetDelayPercentileFieldTrial);
48 double percentile = -1.0;
49 if (sscanf(field_trial_string.c_str(), "Enabled-%lf", &percentile) == 1 &&
50 percentile >= 0.0 && percentile <= 100.0) {
51 return absl::make_optional<int>(static_cast<int>(
52 (1 << 30) * (100.0 - percentile) / 100.0 + 0.5)); // in Q30.
53 } else {
54 RTC_LOG(LS_WARNING) << "Invalid parameter for "
55 << kForceTargetDelayPercentileFieldTrial
56 << ", ignored.";
57 }
58 }
59 return absl::nullopt;
60}
61
62} // namespace
63
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000064namespace webrtc {
65
Peter Kastingdce40cf2015-08-24 14:52:23 -070066DelayManager::DelayManager(size_t max_packets_in_buffer,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010067 int base_min_target_delay_ms,
Jakob Ivarssone98954c2019-02-06 15:37:50 +010068 bool enable_rtx_handling,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070069 DelayPeakDetector* peak_detector,
70 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 : first_packet_received_(false),
72 max_packets_in_buffer_(max_packets_in_buffer),
73 iat_vector_(kMaxIat + 1, 0),
74 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070075 tick_timer_(tick_timer),
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010076 base_min_target_delay_ms_(base_min_target_delay_ms),
Ivo Creusen385b10b2017-10-13 12:37:27 +020077 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000078 target_level_(base_target_level_ << 8), // In Q8 domain.
79 packet_len_ms_(0),
80 streaming_mode_(false),
81 last_seq_no_(0),
82 last_timestamp_(0),
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010083 minimum_delay_ms_(base_min_target_delay_ms_),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000084 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000085 iat_cumulative_sum_(0),
86 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000087 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020088 last_pack_cng_or_dtmf_(1),
89 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +020090 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
Jakob Ivarssone98954c2019-02-06 15:37:50 +010091 forced_limit_probability_(GetForcedLimitProbability()),
92 enable_rtx_handling_(enable_rtx_handling) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 assert(peak_detector); // Should never be NULL.
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010094 RTC_DCHECK_GE(base_min_target_delay_ms_, 0);
95 RTC_DCHECK_LE(minimum_delay_ms_, maximum_delay_ms_);
Minyue Li002fbb82018-10-04 11:31:03 +020096
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 Reset();
98}
99
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000100DelayManager::~DelayManager() {}
101
102const DelayManager::IATVector& DelayManager::iat_vector() const {
103 return iat_vector_;
104}
105
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106// Set the histogram vector to an exponentially decaying distribution
107// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
108// iat_vector_ is in Q30.
109void DelayManager::ResetHistogram() {
110 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
111 // of iat_vector_ is 1.
112 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
113 IATVector::iterator it = iat_vector_.begin();
114 for (; it < iat_vector_.end(); it++) {
115 temp_prob >>= 1;
116 (*it) = temp_prob << 16;
117 }
118 base_target_level_ = 4;
119 target_level_ = base_target_level_ << 8;
120}
121
122int DelayManager::Update(uint16_t sequence_number,
123 uint32_t timestamp,
124 int sample_rate_hz) {
125 if (sample_rate_hz <= 0) {
126 return -1;
127 }
128
129 if (!first_packet_received_) {
130 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700131 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 last_seq_no_ = sequence_number;
133 last_timestamp_ = timestamp;
134 first_packet_received_ = true;
135 return 0;
136 }
137
138 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000139 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000140 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
141 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000142 // Wrong timestamp or sequence order; use stored value.
143 packet_len_ms = packet_len_ms_;
144 } else {
145 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800146 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000147 static_cast<uint32_t>(timestamp - last_timestamp_) /
148 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800149 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700150 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151 }
152
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100153 bool reordered = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000154 if (packet_len_ms > 0) {
155 // Cannot update statistics unless |packet_len_ms| is valid.
156 // Calculate inter-arrival time (IAT) in integer "packet times"
157 // (rounding down). This is the value used as index to the histogram
158 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700159 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160
161 if (streaming_mode_) {
162 UpdateCumulativeSums(packet_len_ms, sequence_number);
163 }
164
165 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000166 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 // Compensate for gap in the sequence numbers. Reduce IAT with the
168 // expected extra time due to lost packets, but ensure that the IAT is
169 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000170 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000172 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
173 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100174 reordered = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000175 }
176
177 // Saturate IAT at maximum value.
178 const int max_iat = kMaxIat;
179 iat_packets = std::min(iat_packets, max_iat);
180 UpdateHistogram(iat_packets);
181 // Calculate new |target_level_| based on updated statistics.
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100182 target_level_ = CalculateTargetLevel(iat_packets, reordered);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 if (streaming_mode_) {
184 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
185 }
186
187 LimitTargetLevel();
188 } // End if (packet_len_ms > 0).
189
Jakob Ivarssone98954c2019-02-06 15:37:50 +0100190 if (enable_rtx_handling_ && reordered &&
191 num_reordered_packets_ < kMaxReorderedPackets) {
192 ++num_reordered_packets_;
193 return 0;
194 }
195 num_reordered_packets_ = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700197 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000198 last_seq_no_ = sequence_number;
199 last_timestamp_ = timestamp;
200 return 0;
201}
202
203void DelayManager::UpdateCumulativeSums(int packet_len_ms,
204 uint16_t sequence_number) {
205 // Calculate IAT in Q8, including fractions of a packet (i.e., more
206 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700207 int iat_packets_q8 =
208 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000209 // Calculate cumulative sum IAT with sequence number compensation. The sum
210 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200211 iat_cumulative_sum_ +=
212 (iat_packets_q8 -
213 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 // Subtract drift term.
215 iat_cumulative_sum_ -= kCumulativeSumDrift;
216 // Ensure not negative.
217 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
218 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
219 // Found a new maximum.
220 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700221 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000222 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700223 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000224 // Too long since the last maximum was observed; decrease max value.
225 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
226 }
227}
228
229// Each element in the vector is first multiplied by the forgetting factor
230// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
231// increased (additive) by 1 - |iat_factor_|. This way, the probability of
232// |iat_packets| is slightly increased, while the sum of the histogram remains
233// constant (=1).
234// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
235// longer sum up to 1 (in Q30) after the update. To correct this, a correction
236// term is added or subtracted from the first element (or elements) of the
237// vector.
238// The forgetting factor |iat_factor_| is also updated. When the DelayManager
239// is reset, the factor is set to 0 to facilitate rapid convergence in the
240// beginning. With each update of the histogram, the factor is increased towards
241// the steady-state value |kIatFactor_|.
242void DelayManager::UpdateHistogram(size_t iat_packets) {
243 assert(iat_packets < iat_vector_.size());
244 int vector_sum = 0; // Sum up the vector elements as they are processed.
245 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200246 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
247 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000248 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
249 vector_sum += *it;
250 }
251
252 // Increase the probability for the currently observed inter-arrival time
253 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
254 // Thus, left-shift 15 steps to obtain result in Q30.
255 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
256 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
257
258 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
259 // fixed-point rounding errors.
260 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
261 if (vector_sum != 0) {
262 // Modify a few values early in |iat_vector_|.
263 int flip_sign = vector_sum > 0 ? -1 : 1;
264 IATVector::iterator it = iat_vector_.begin();
265 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
266 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
267 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
268 *it += correction;
269 vector_sum += correction;
270 ++it;
271 }
272 }
273 assert(vector_sum == 0); // Verify that the above is correct.
274
275 // Update |iat_factor_| (changes only during the first seconds after a reset).
276 // The factor converges to |kIatFactor_|.
277 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
278}
279
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000280// Enforces upper and lower limits for |target_level_|. The upper limit is
281// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
282// headroom for natural fluctuations around the target, and ii) equivalent of
283// |maximum_delay_ms_| in packets. Note that in practice, if no
284// |maximum_delay_ms_| is specified, this does not have any impact, since the
285// target level is far below the buffer capacity in all reasonable cases.
286// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
287// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000288// TODO(hlundin): Move this check to the buffer logistics class.
289void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000290 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200291 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000292 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000294
295 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
296 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
297 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
298 }
299
300 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700301 int max_buffer_packets_q8 =
302 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 target_level_ = std::min(target_level_, max_buffer_packets_q8);
304
305 // Sanity check, at least 1 packet (in Q8).
306 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000307}
308
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100309int DelayManager::CalculateTargetLevel(int iat_packets, bool reordered) {
Minyue Li002fbb82018-10-04 11:31:03 +0200310 int limit_probability = forced_limit_probability_.value_or(kLimitProbability);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311 if (streaming_mode_) {
312 limit_probability = kLimitProbabilityStreaming;
313 }
314
315 // Calculate target buffer level from inter-arrival time histogram.
316 // Find the |iat_index| for which the probability of observing an
317 // inter-arrival time larger than or equal to |iat_index| is less than or
318 // equal to |limit_probability|. The sought probability is estimated using
319 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
320 // the end up until |iat_index|. Now, since the sum of all elements is 1
321 // (in Q30) by definition, and since the solution is often a low value for
322 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
323 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200324 size_t index = 0; // Start from the beginning of |iat_vector_|.
325 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000326 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
327
328 do {
329 // Subtract the probabilities one by one until the sum is no longer greater
330 // than limit_probability.
331 ++index;
332 sum -= iat_vector_[index];
333 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
334
335 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000336 int target_level = static_cast<int>(index);
337 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000338
339 // Update detector for delay peaks.
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100340 bool delay_peak_found =
341 peak_detector_.Update(iat_packets, reordered, target_level);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000342 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000343 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000344 }
345
346 // Sanity check. |target_level| must be strictly positive.
347 target_level = std::max(target_level, 1);
348 // Scale to Q8 and assign to member variable.
349 target_level_ = target_level << 8;
350 return target_level_;
351}
352
353int DelayManager::SetPacketAudioLength(int length_ms) {
354 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356 return -1;
357 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200358 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
359 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
360 }
361
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 packet_len_ms_ = length_ms;
363 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700364 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000365 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
366 return 0;
367}
368
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369void DelayManager::Reset() {
370 packet_len_ms_ = 0; // Packet size unknown.
371 streaming_mode_ = false;
372 peak_detector_.Reset();
373 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200374 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700375 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
376 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000377 iat_cumulative_sum_ = 0;
378 max_iat_cumulative_sum_ = 0;
379 last_pack_cng_or_dtmf_ = 1;
380}
381
henrik.lundin0d838572016-10-13 03:35:55 -0700382double DelayManager::EstimatedClockDriftPpm() const {
383 double sum = 0.0;
384 // Calculate the expected value based on the probabilities in |iat_vector_|.
385 for (size_t i = 0; i < iat_vector_.size(); ++i) {
386 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 }
henrik.lundin0d838572016-10-13 03:35:55 -0700388 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
389 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
390 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
391 // (ppm).
392 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393}
394
395bool DelayManager::PeakFound() const {
396 return peak_detector_.peak_found();
397}
398
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700399void DelayManager::ResetPacketIatCount() {
400 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401}
402
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000403// Note that |low_limit| and |higher_limit| are not assigned to
404// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
405// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000406void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
407 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100408 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 assert(false);
410 return;
411 }
412
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
414 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415 window_20ms = (20 << 8) / packet_len_ms_;
416 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000417
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000419 *lower_limit = (target_level_ * 3) / 4;
420 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000421 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000422 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000423}
424
425int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000426 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427}
428
ossuf1b08da2016-09-23 02:19:43 -0700429void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
430 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000431 last_pack_cng_or_dtmf_ = 1;
432 } else if (last_pack_cng_or_dtmf_ != 0) {
433 last_pack_cng_or_dtmf_ = -1;
434 }
435}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000436
henrik.lundinb8c55b12017-05-10 07:38:01 -0700437void DelayManager::RegisterEmptyPacket() {
438 ++last_seq_no_;
439}
440
Ivo Creusen385b10b2017-10-13 12:37:27 +0200441DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
442 int old_packet_length,
443 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200444 if (old_packet_length == 0) {
445 // If we don't know the previous frame length, don't make any changes to the
446 // histogram.
447 return histogram;
448 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200449 RTC_DCHECK_GT(new_packet_length, 0);
450 RTC_DCHECK_EQ(old_packet_length % 10, 0);
451 RTC_DCHECK_EQ(new_packet_length % 10, 0);
452 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100453 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200454 int time_counter = 0;
455 size_t new_histogram_idx = 0;
456 for (size_t i = 0; i < histogram.size(); i++) {
457 acc += histogram[i];
458 time_counter += old_packet_length;
459 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100460 const int64_t scaled_acc = acc * new_packet_length / time_counter;
461 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200462 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100463 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
464 new_histogram[new_histogram_idx] =
465 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
466 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200467 new_histogram_idx =
468 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
469 time_counter -= new_packet_length;
470 }
471 // Only subtract the part that was succesfully written to the new histogram.
472 acc -= actually_used_acc;
473 }
474 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100475 // last bin. If we cannot add everything to the last bin we need to add as
476 // much as possible to the bins after the last bin (this is only possible
477 // when compressing a histogram).
478 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
479 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
480 new_histogram[new_histogram_idx] =
481 rtc::saturated_cast<int>(old_histogram_val + acc);
482 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
483 new_histogram_idx++;
484 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200485 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100486 if (acc == 0) {
487 // If acc is non-zero, we were not able to add everything to the new
488 // histogram, so this check will not hold.
489 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
490 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
491 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200492 return new_histogram;
493}
494
Ruslan Burakovedbea462019-02-04 16:17:31 +0100495bool DelayManager::IsValidMinimumDelay(int delay_ms) {
496 const int q75 =
497 rtc::dchecked_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4);
498 return delay_ms >= 0 &&
499 (maximum_delay_ms_ <= 0 || delay_ms <= maximum_delay_ms_) &&
500 (packet_len_ms_ <= 0 || delay_ms <= q75);
501}
502
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000503bool DelayManager::SetMinimumDelay(int delay_ms) {
Ruslan Burakovedbea462019-02-04 16:17:31 +0100504 if (!IsValidMinimumDelay(delay_ms)) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000505 return false;
506 }
Ruslan Burakovedbea462019-02-04 16:17:31 +0100507 // Ensure that minimum_delay_ms is no bigger than base_min_target_delay_ms_
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100508 minimum_delay_ms_ = std::max(delay_ms, base_min_target_delay_ms_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000509 return true;
510}
511
512bool DelayManager::SetMaximumDelay(int delay_ms) {
513 if (delay_ms == 0) {
514 // Zero input unsets the maximum delay.
515 maximum_delay_ms_ = 0;
516 return true;
517 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
518 // Maximum delay shouldn't be less than minimum delay or less than a packet.
519 return false;
520 }
521 maximum_delay_ms_ = delay_ms;
522 return true;
523}
524
Ruslan Burakovedbea462019-02-04 16:17:31 +0100525bool DelayManager::SetBaseMinimumDelay(int delay_ms) {
526 if (!IsValidMinimumDelay(delay_ms)) {
527 return false;
528 }
529
530 base_min_target_delay_ms_ = delay_ms;
531 // Ensure that minimum_delay_ms is no bigger than base_min_target_delay_ms_
532 minimum_delay_ms_ = std::max(delay_ms, base_min_target_delay_ms_);
533 return true;
534}
535
536int DelayManager::GetBaseMinimumDelay() const {
537 return base_min_target_delay_ms_;
538}
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}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553} // namespace webrtc