blob: 67e6a13c1d769526d1718224a877c2e642dc93a7 [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.
37
38absl::optional<int> GetForcedLimitProbability() {
39 constexpr char kForceTargetDelayPercentileFieldTrial[] =
40 "WebRTC-Audio-NetEqForceTargetDelayPercentile";
41 const bool use_forced_target_delay_percentile =
42 webrtc::field_trial::IsEnabled(kForceTargetDelayPercentileFieldTrial);
43 if (use_forced_target_delay_percentile) {
44 const std::string field_trial_string = webrtc::field_trial::FindFullName(
45 kForceTargetDelayPercentileFieldTrial);
46 double percentile = -1.0;
47 if (sscanf(field_trial_string.c_str(), "Enabled-%lf", &percentile) == 1 &&
48 percentile >= 0.0 && percentile <= 100.0) {
49 return absl::make_optional<int>(static_cast<int>(
50 (1 << 30) * (100.0 - percentile) / 100.0 + 0.5)); // in Q30.
51 } else {
52 RTC_LOG(LS_WARNING) << "Invalid parameter for "
53 << kForceTargetDelayPercentileFieldTrial
54 << ", ignored.";
55 }
56 }
57 return absl::nullopt;
58}
59
60} // namespace
61
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000062namespace webrtc {
63
Peter Kastingdce40cf2015-08-24 14:52:23 -070064DelayManager::DelayManager(size_t max_packets_in_buffer,
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010065 int base_min_target_delay_ms,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070066 DelayPeakDetector* peak_detector,
67 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068 : first_packet_received_(false),
69 max_packets_in_buffer_(max_packets_in_buffer),
70 iat_vector_(kMaxIat + 1, 0),
71 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070072 tick_timer_(tick_timer),
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010073 base_min_target_delay_ms_(base_min_target_delay_ms),
Ivo Creusen385b10b2017-10-13 12:37:27 +020074 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000075 target_level_(base_target_level_ << 8), // In Q8 domain.
76 packet_len_ms_(0),
77 streaming_mode_(false),
78 last_seq_no_(0),
79 last_timestamp_(0),
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010080 minimum_delay_ms_(base_min_target_delay_ms_),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000081 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 iat_cumulative_sum_(0),
83 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020085 last_pack_cng_or_dtmf_(1),
86 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +020087 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
88 forced_limit_probability_(GetForcedLimitProbability()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 assert(peak_detector); // Should never be NULL.
Jakob Ivarsson10403ae2018-11-27 15:45:20 +010090 RTC_DCHECK_GE(base_min_target_delay_ms_, 0);
91 RTC_DCHECK_LE(minimum_delay_ms_, maximum_delay_ms_);
Minyue Li002fbb82018-10-04 11:31:03 +020092
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 Reset();
94}
95
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000096DelayManager::~DelayManager() {}
97
98const DelayManager::IATVector& DelayManager::iat_vector() const {
99 return iat_vector_;
100}
101
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102// Set the histogram vector to an exponentially decaying distribution
103// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
104// iat_vector_ is in Q30.
105void DelayManager::ResetHistogram() {
106 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
107 // of iat_vector_ is 1.
108 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
109 IATVector::iterator it = iat_vector_.begin();
110 for (; it < iat_vector_.end(); it++) {
111 temp_prob >>= 1;
112 (*it) = temp_prob << 16;
113 }
114 base_target_level_ = 4;
115 target_level_ = base_target_level_ << 8;
116}
117
118int DelayManager::Update(uint16_t sequence_number,
119 uint32_t timestamp,
120 int sample_rate_hz) {
121 if (sample_rate_hz <= 0) {
122 return -1;
123 }
124
125 if (!first_packet_received_) {
126 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700127 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 last_seq_no_ = sequence_number;
129 last_timestamp_ = timestamp;
130 first_packet_received_ = true;
131 return 0;
132 }
133
134 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000136 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
137 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000138 // Wrong timestamp or sequence order; use stored value.
139 packet_len_ms = packet_len_ms_;
140 } else {
141 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800142 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000143 static_cast<uint32_t>(timestamp - last_timestamp_) /
144 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800145 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700146 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000147 }
148
149 if (packet_len_ms > 0) {
150 // Cannot update statistics unless |packet_len_ms| is valid.
151 // Calculate inter-arrival time (IAT) in integer "packet times"
152 // (rounding down). This is the value used as index to the histogram
153 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700154 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000155
156 if (streaming_mode_) {
157 UpdateCumulativeSums(packet_len_ms, sequence_number);
158 }
159
160 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000161 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000162 // Compensate for gap in the sequence numbers. Reduce IAT with the
163 // expected extra time due to lost packets, but ensure that the IAT is
164 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000165 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000167 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
168 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000169 }
170
171 // Saturate IAT at maximum value.
172 const int max_iat = kMaxIat;
173 iat_packets = std::min(iat_packets, max_iat);
174 UpdateHistogram(iat_packets);
175 // Calculate new |target_level_| based on updated statistics.
176 target_level_ = CalculateTargetLevel(iat_packets);
177 if (streaming_mode_) {
178 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
179 }
180
181 LimitTargetLevel();
182 } // End if (packet_len_ms > 0).
183
184 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700185 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000186 last_seq_no_ = sequence_number;
187 last_timestamp_ = timestamp;
188 return 0;
189}
190
191void DelayManager::UpdateCumulativeSums(int packet_len_ms,
192 uint16_t sequence_number) {
193 // Calculate IAT in Q8, including fractions of a packet (i.e., more
194 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700195 int iat_packets_q8 =
196 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 // Calculate cumulative sum IAT with sequence number compensation. The sum
198 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200199 iat_cumulative_sum_ +=
200 (iat_packets_q8 -
201 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000202 // Subtract drift term.
203 iat_cumulative_sum_ -= kCumulativeSumDrift;
204 // Ensure not negative.
205 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
206 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
207 // Found a new maximum.
208 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700209 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700211 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 // Too long since the last maximum was observed; decrease max value.
213 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
214 }
215}
216
217// Each element in the vector is first multiplied by the forgetting factor
218// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
219// increased (additive) by 1 - |iat_factor_|. This way, the probability of
220// |iat_packets| is slightly increased, while the sum of the histogram remains
221// constant (=1).
222// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
223// longer sum up to 1 (in Q30) after the update. To correct this, a correction
224// term is added or subtracted from the first element (or elements) of the
225// vector.
226// The forgetting factor |iat_factor_| is also updated. When the DelayManager
227// is reset, the factor is set to 0 to facilitate rapid convergence in the
228// beginning. With each update of the histogram, the factor is increased towards
229// the steady-state value |kIatFactor_|.
230void DelayManager::UpdateHistogram(size_t iat_packets) {
231 assert(iat_packets < iat_vector_.size());
232 int vector_sum = 0; // Sum up the vector elements as they are processed.
233 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200234 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
235 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000236 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
237 vector_sum += *it;
238 }
239
240 // Increase the probability for the currently observed inter-arrival time
241 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
242 // Thus, left-shift 15 steps to obtain result in Q30.
243 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
244 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
245
246 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
247 // fixed-point rounding errors.
248 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
249 if (vector_sum != 0) {
250 // Modify a few values early in |iat_vector_|.
251 int flip_sign = vector_sum > 0 ? -1 : 1;
252 IATVector::iterator it = iat_vector_.begin();
253 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
254 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
255 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
256 *it += correction;
257 vector_sum += correction;
258 ++it;
259 }
260 }
261 assert(vector_sum == 0); // Verify that the above is correct.
262
263 // Update |iat_factor_| (changes only during the first seconds after a reset).
264 // The factor converges to |kIatFactor_|.
265 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
266}
267
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268// Enforces upper and lower limits for |target_level_|. The upper limit is
269// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
270// headroom for natural fluctuations around the target, and ii) equivalent of
271// |maximum_delay_ms_| in packets. Note that in practice, if no
272// |maximum_delay_ms_| is specified, this does not have any impact, since the
273// target level is far below the buffer capacity in all reasonable cases.
274// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
275// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276// TODO(hlundin): Move this check to the buffer logistics class.
277void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000278 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200279 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000280 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000281 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000282
283 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
284 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
285 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
286 }
287
288 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700289 int max_buffer_packets_q8 =
290 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000291 target_level_ = std::min(target_level_, max_buffer_packets_q8);
292
293 // Sanity check, at least 1 packet (in Q8).
294 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295}
296
297int DelayManager::CalculateTargetLevel(int iat_packets) {
Minyue Li002fbb82018-10-04 11:31:03 +0200298 int limit_probability = forced_limit_probability_.value_or(kLimitProbability);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 if (streaming_mode_) {
300 limit_probability = kLimitProbabilityStreaming;
301 }
302
303 // Calculate target buffer level from inter-arrival time histogram.
304 // Find the |iat_index| for which the probability of observing an
305 // inter-arrival time larger than or equal to |iat_index| is less than or
306 // equal to |limit_probability|. The sought probability is estimated using
307 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
308 // the end up until |iat_index|. Now, since the sum of all elements is 1
309 // (in Q30) by definition, and since the solution is often a low value for
310 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
311 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200312 size_t index = 0; // Start from the beginning of |iat_vector_|.
313 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
315
316 do {
317 // Subtract the probabilities one by one until the sum is no longer greater
318 // than limit_probability.
319 ++index;
320 sum -= iat_vector_[index];
321 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
322
323 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000324 int target_level = static_cast<int>(index);
325 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000326
327 // Update detector for delay peaks.
328 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
329 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000330 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 }
332
333 // Sanity check. |target_level| must be strictly positive.
334 target_level = std::max(target_level, 1);
335 // Scale to Q8 and assign to member variable.
336 target_level_ = target_level << 8;
337 return target_level_;
338}
339
340int DelayManager::SetPacketAudioLength(int length_ms) {
341 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100342 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 return -1;
344 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200345 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
346 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
347 }
348
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349 packet_len_ms_ = length_ms;
350 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700351 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
353 return 0;
354}
355
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356void DelayManager::Reset() {
357 packet_len_ms_ = 0; // Packet size unknown.
358 streaming_mode_ = false;
359 peak_detector_.Reset();
360 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200361 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700362 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
363 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 iat_cumulative_sum_ = 0;
365 max_iat_cumulative_sum_ = 0;
366 last_pack_cng_or_dtmf_ = 1;
367}
368
henrik.lundin0d838572016-10-13 03:35:55 -0700369double DelayManager::EstimatedClockDriftPpm() const {
370 double sum = 0.0;
371 // Calculate the expected value based on the probabilities in |iat_vector_|.
372 for (size_t i = 0; i < iat_vector_.size(); ++i) {
373 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374 }
henrik.lundin0d838572016-10-13 03:35:55 -0700375 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
376 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
377 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
378 // (ppm).
379 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380}
381
382bool DelayManager::PeakFound() const {
383 return peak_detector_.peak_found();
384}
385
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700386void DelayManager::ResetPacketIatCount() {
387 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000388}
389
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000390// Note that |low_limit| and |higher_limit| are not assigned to
391// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
392// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
394 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100395 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000396 assert(false);
397 return;
398 }
399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
401 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 window_20ms = (20 << 8) / packet_len_ms_;
403 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000404
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000406 *lower_limit = (target_level_ * 3) / 4;
407 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000408 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000409 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000410}
411
412int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000413 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000414}
415
ossuf1b08da2016-09-23 02:19:43 -0700416void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
417 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 last_pack_cng_or_dtmf_ = 1;
419 } else if (last_pack_cng_or_dtmf_ != 0) {
420 last_pack_cng_or_dtmf_ = -1;
421 }
422}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000423
henrik.lundinb8c55b12017-05-10 07:38:01 -0700424void DelayManager::RegisterEmptyPacket() {
425 ++last_seq_no_;
426}
427
Ivo Creusen385b10b2017-10-13 12:37:27 +0200428DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
429 int old_packet_length,
430 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200431 if (old_packet_length == 0) {
432 // If we don't know the previous frame length, don't make any changes to the
433 // histogram.
434 return histogram;
435 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200436 RTC_DCHECK_GT(new_packet_length, 0);
437 RTC_DCHECK_EQ(old_packet_length % 10, 0);
438 RTC_DCHECK_EQ(new_packet_length % 10, 0);
439 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100440 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200441 int time_counter = 0;
442 size_t new_histogram_idx = 0;
443 for (size_t i = 0; i < histogram.size(); i++) {
444 acc += histogram[i];
445 time_counter += old_packet_length;
446 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100447 const int64_t scaled_acc = acc * new_packet_length / time_counter;
448 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200449 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100450 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
451 new_histogram[new_histogram_idx] =
452 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
453 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200454 new_histogram_idx =
455 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
456 time_counter -= new_packet_length;
457 }
458 // Only subtract the part that was succesfully written to the new histogram.
459 acc -= actually_used_acc;
460 }
461 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100462 // last bin. If we cannot add everything to the last bin we need to add as
463 // much as possible to the bins after the last bin (this is only possible
464 // when compressing a histogram).
465 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
466 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
467 new_histogram[new_histogram_idx] =
468 rtc::saturated_cast<int>(old_histogram_val + acc);
469 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
470 new_histogram_idx++;
471 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200472 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100473 if (acc == 0) {
474 // If acc is non-zero, we were not able to add everything to the new
475 // histogram, so this check will not hold.
476 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
477 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
478 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200479 return new_histogram;
480}
481
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000482bool DelayManager::SetMinimumDelay(int delay_ms) {
483 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
484 // Also, if possible check |delay| to less than 75% of
485 // |max_packets_in_buffer_|.
486 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
487 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700488 delay_ms >
489 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000490 return false;
491 }
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100492 minimum_delay_ms_ = std::max(delay_ms, base_min_target_delay_ms_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000493 return true;
494}
495
496bool DelayManager::SetMaximumDelay(int delay_ms) {
497 if (delay_ms == 0) {
498 // Zero input unsets the maximum delay.
499 maximum_delay_ms_ = 0;
500 return true;
501 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
502 // Maximum delay shouldn't be less than minimum delay or less than a packet.
503 return false;
504 }
505 maximum_delay_ms_ = delay_ms;
506 return true;
507}
508
Yves Gerey665174f2018-06-19 15:03:05 +0200509int DelayManager::base_target_level() const {
510 return base_target_level_;
511}
512void DelayManager::set_streaming_mode(bool value) {
513 streaming_mode_ = value;
514}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000515int DelayManager::last_pack_cng_or_dtmf() const {
516 return last_pack_cng_or_dtmf_;
517}
518
519void DelayManager::set_last_pack_cng_or_dtmf(int value) {
520 last_pack_cng_or_dtmf_ = value;
521}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000522} // namespace webrtc