blob: e5eb592efa1347565b62b0b19da75f71a3200dd3 [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>
14#include <math.h>
15
16#include <algorithm> // max, min
Ivo Creusen385b10b2017-10-13 12:37:27 +020017#include <numeric>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "common_audio/signal_processing/include/signal_processing_library.h"
20#include "modules/audio_coding/neteq/delay_peak_detector.h"
21#include "modules/include/module_common_types.h"
22#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010023#include "rtc_base/numerics/safe_conversions.h"
Ivo Creusen385b10b2017-10-13 12:37:27 +020024#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000025
Minyue Li002fbb82018-10-04 11:31:03 +020026namespace {
27
28constexpr int kLimitProbability = 53687091; // 1/20 in Q30.
29constexpr int kLimitProbabilityStreaming = 536871; // 1/2000 in Q30.
30constexpr int kMaxStreamingPeakPeriodMs = 600000; // 10 minutes in ms.
31constexpr int kCumulativeSumDrift = 2; // Drift term for cumulative sum
32 // |iat_cumulative_sum_|.
33// Steady-state forgetting factor for |iat_vector_|, 0.9993 in Q15.
34constexpr int kIatFactor_ = 32745;
35constexpr int kMaxIat = 64; // Max inter-arrival time to register.
36
37absl::optional<int> GetForcedLimitProbability() {
38 constexpr char kForceTargetDelayPercentileFieldTrial[] =
39 "WebRTC-Audio-NetEqForceTargetDelayPercentile";
40 const bool use_forced_target_delay_percentile =
41 webrtc::field_trial::IsEnabled(kForceTargetDelayPercentileFieldTrial);
42 if (use_forced_target_delay_percentile) {
43 const std::string field_trial_string = webrtc::field_trial::FindFullName(
44 kForceTargetDelayPercentileFieldTrial);
45 double percentile = -1.0;
46 if (sscanf(field_trial_string.c_str(), "Enabled-%lf", &percentile) == 1 &&
47 percentile >= 0.0 && percentile <= 100.0) {
48 return absl::make_optional<int>(static_cast<int>(
49 (1 << 30) * (100.0 - percentile) / 100.0 + 0.5)); // in Q30.
50 } else {
51 RTC_LOG(LS_WARNING) << "Invalid parameter for "
52 << kForceTargetDelayPercentileFieldTrial
53 << ", ignored.";
54 }
55 }
56 return absl::nullopt;
57}
58
59} // namespace
60
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000061namespace webrtc {
62
Peter Kastingdce40cf2015-08-24 14:52:23 -070063DelayManager::DelayManager(size_t max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070064 DelayPeakDetector* peak_detector,
65 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000066 : first_packet_received_(false),
67 max_packets_in_buffer_(max_packets_in_buffer),
68 iat_vector_(kMaxIat + 1, 0),
69 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070070 tick_timer_(tick_timer),
Ivo Creusen385b10b2017-10-13 12:37:27 +020071 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000072 target_level_(base_target_level_ << 8), // In Q8 domain.
73 packet_len_ms_(0),
74 streaming_mode_(false),
75 last_seq_no_(0),
76 last_timestamp_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000077 minimum_delay_ms_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000078 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000079 iat_cumulative_sum_(0),
80 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000081 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020082 last_pack_cng_or_dtmf_(1),
83 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +020084 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
85 forced_limit_probability_(GetForcedLimitProbability()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000086 assert(peak_detector); // Should never be NULL.
Minyue Li002fbb82018-10-04 11:31:03 +020087
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000088 Reset();
89}
90
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000091DelayManager::~DelayManager() {}
92
93const DelayManager::IATVector& DelayManager::iat_vector() const {
94 return iat_vector_;
95}
96
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097// Set the histogram vector to an exponentially decaying distribution
98// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
99// iat_vector_ is in Q30.
100void DelayManager::ResetHistogram() {
101 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
102 // of iat_vector_ is 1.
103 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
104 IATVector::iterator it = iat_vector_.begin();
105 for (; it < iat_vector_.end(); it++) {
106 temp_prob >>= 1;
107 (*it) = temp_prob << 16;
108 }
109 base_target_level_ = 4;
110 target_level_ = base_target_level_ << 8;
111}
112
113int DelayManager::Update(uint16_t sequence_number,
114 uint32_t timestamp,
115 int sample_rate_hz) {
116 if (sample_rate_hz <= 0) {
117 return -1;
118 }
119
120 if (!first_packet_received_) {
121 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700122 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123 last_seq_no_ = sequence_number;
124 last_timestamp_ = timestamp;
125 first_packet_received_ = true;
126 return 0;
127 }
128
129 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000131 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
132 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133 // Wrong timestamp or sequence order; use stored value.
134 packet_len_ms = packet_len_ms_;
135 } else {
136 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800137 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000138 static_cast<uint32_t>(timestamp - last_timestamp_) /
139 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800140 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700141 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000142 }
143
144 if (packet_len_ms > 0) {
145 // Cannot update statistics unless |packet_len_ms| is valid.
146 // Calculate inter-arrival time (IAT) in integer "packet times"
147 // (rounding down). This is the value used as index to the histogram
148 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700149 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150
151 if (streaming_mode_) {
152 UpdateCumulativeSums(packet_len_ms, sequence_number);
153 }
154
155 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000156 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 // Compensate for gap in the sequence numbers. Reduce IAT with the
158 // expected extra time due to lost packets, but ensure that the IAT is
159 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000160 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000161 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000162 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
163 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 }
165
166 // Saturate IAT at maximum value.
167 const int max_iat = kMaxIat;
168 iat_packets = std::min(iat_packets, max_iat);
169 UpdateHistogram(iat_packets);
170 // Calculate new |target_level_| based on updated statistics.
171 target_level_ = CalculateTargetLevel(iat_packets);
172 if (streaming_mode_) {
173 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
174 }
175
176 LimitTargetLevel();
177 } // End if (packet_len_ms > 0).
178
179 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700180 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000181 last_seq_no_ = sequence_number;
182 last_timestamp_ = timestamp;
183 return 0;
184}
185
186void DelayManager::UpdateCumulativeSums(int packet_len_ms,
187 uint16_t sequence_number) {
188 // Calculate IAT in Q8, including fractions of a packet (i.e., more
189 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700190 int iat_packets_q8 =
191 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000192 // Calculate cumulative sum IAT with sequence number compensation. The sum
193 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200194 iat_cumulative_sum_ +=
195 (iat_packets_q8 -
196 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 // Subtract drift term.
198 iat_cumulative_sum_ -= kCumulativeSumDrift;
199 // Ensure not negative.
200 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
201 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
202 // Found a new maximum.
203 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700204 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000205 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700206 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 // Too long since the last maximum was observed; decrease max value.
208 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
209 }
210}
211
212// Each element in the vector is first multiplied by the forgetting factor
213// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
214// increased (additive) by 1 - |iat_factor_|. This way, the probability of
215// |iat_packets| is slightly increased, while the sum of the histogram remains
216// constant (=1).
217// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
218// longer sum up to 1 (in Q30) after the update. To correct this, a correction
219// term is added or subtracted from the first element (or elements) of the
220// vector.
221// The forgetting factor |iat_factor_| is also updated. When the DelayManager
222// is reset, the factor is set to 0 to facilitate rapid convergence in the
223// beginning. With each update of the histogram, the factor is increased towards
224// the steady-state value |kIatFactor_|.
225void DelayManager::UpdateHistogram(size_t iat_packets) {
226 assert(iat_packets < iat_vector_.size());
227 int vector_sum = 0; // Sum up the vector elements as they are processed.
228 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200229 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
230 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000231 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
232 vector_sum += *it;
233 }
234
235 // Increase the probability for the currently observed inter-arrival time
236 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
237 // Thus, left-shift 15 steps to obtain result in Q30.
238 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
239 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
240
241 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
242 // fixed-point rounding errors.
243 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
244 if (vector_sum != 0) {
245 // Modify a few values early in |iat_vector_|.
246 int flip_sign = vector_sum > 0 ? -1 : 1;
247 IATVector::iterator it = iat_vector_.begin();
248 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
249 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
250 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
251 *it += correction;
252 vector_sum += correction;
253 ++it;
254 }
255 }
256 assert(vector_sum == 0); // Verify that the above is correct.
257
258 // Update |iat_factor_| (changes only during the first seconds after a reset).
259 // The factor converges to |kIatFactor_|.
260 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
261}
262
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263// Enforces upper and lower limits for |target_level_|. The upper limit is
264// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
265// headroom for natural fluctuations around the target, and ii) equivalent of
266// |maximum_delay_ms_| in packets. Note that in practice, if no
267// |maximum_delay_ms_| is specified, this does not have any impact, since the
268// target level is far below the buffer capacity in all reasonable cases.
269// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
270// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000271// TODO(hlundin): Move this check to the buffer logistics class.
272void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000273 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200274 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000275 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000277
278 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
279 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
280 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
281 }
282
283 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700284 int max_buffer_packets_q8 =
285 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000286 target_level_ = std::min(target_level_, max_buffer_packets_q8);
287
288 // Sanity check, at least 1 packet (in Q8).
289 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000290}
291
292int DelayManager::CalculateTargetLevel(int iat_packets) {
Minyue Li002fbb82018-10-04 11:31:03 +0200293 int limit_probability = forced_limit_probability_.value_or(kLimitProbability);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000294 if (streaming_mode_) {
295 limit_probability = kLimitProbabilityStreaming;
296 }
297
298 // Calculate target buffer level from inter-arrival time histogram.
299 // Find the |iat_index| for which the probability of observing an
300 // inter-arrival time larger than or equal to |iat_index| is less than or
301 // equal to |limit_probability|. The sought probability is estimated using
302 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
303 // the end up until |iat_index|. Now, since the sum of all elements is 1
304 // (in Q30) by definition, and since the solution is often a low value for
305 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
306 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200307 size_t index = 0; // Start from the beginning of |iat_vector_|.
308 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
310
311 do {
312 // Subtract the probabilities one by one until the sum is no longer greater
313 // than limit_probability.
314 ++index;
315 sum -= iat_vector_[index];
316 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
317
318 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000319 int target_level = static_cast<int>(index);
320 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321
322 // Update detector for delay peaks.
323 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
324 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000325 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000326 }
327
328 // Sanity check. |target_level| must be strictly positive.
329 target_level = std::max(target_level, 1);
330 // Scale to Q8 and assign to member variable.
331 target_level_ = target_level << 8;
332 return target_level_;
333}
334
335int DelayManager::SetPacketAudioLength(int length_ms) {
336 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100337 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000338 return -1;
339 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200340 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
341 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
342 }
343
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000344 packet_len_ms_ = length_ms;
345 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700346 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000347 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
348 return 0;
349}
350
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351void DelayManager::Reset() {
352 packet_len_ms_ = 0; // Packet size unknown.
353 streaming_mode_ = false;
354 peak_detector_.Reset();
355 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200356 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700357 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
358 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 iat_cumulative_sum_ = 0;
360 max_iat_cumulative_sum_ = 0;
361 last_pack_cng_or_dtmf_ = 1;
362}
363
henrik.lundin0d838572016-10-13 03:35:55 -0700364double DelayManager::EstimatedClockDriftPpm() const {
365 double sum = 0.0;
366 // Calculate the expected value based on the probabilities in |iat_vector_|.
367 for (size_t i = 0; i < iat_vector_.size(); ++i) {
368 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369 }
henrik.lundin0d838572016-10-13 03:35:55 -0700370 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
371 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
372 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
373 // (ppm).
374 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000375}
376
377bool DelayManager::PeakFound() const {
378 return peak_detector_.peak_found();
379}
380
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700381void DelayManager::ResetPacketIatCount() {
382 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383}
384
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000385// Note that |low_limit| and |higher_limit| are not assigned to
386// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
387// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000388void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
389 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100390 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 assert(false);
392 return;
393 }
394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
396 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 window_20ms = (20 << 8) / packet_len_ms_;
398 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000401 *lower_limit = (target_level_ * 3) / 4;
402 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000403 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000404 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405}
406
407int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000408 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409}
410
ossuf1b08da2016-09-23 02:19:43 -0700411void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
412 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413 last_pack_cng_or_dtmf_ = 1;
414 } else if (last_pack_cng_or_dtmf_ != 0) {
415 last_pack_cng_or_dtmf_ = -1;
416 }
417}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000418
henrik.lundinb8c55b12017-05-10 07:38:01 -0700419void DelayManager::RegisterEmptyPacket() {
420 ++last_seq_no_;
421}
422
Ivo Creusen385b10b2017-10-13 12:37:27 +0200423DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
424 int old_packet_length,
425 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200426 if (old_packet_length == 0) {
427 // If we don't know the previous frame length, don't make any changes to the
428 // histogram.
429 return histogram;
430 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200431 RTC_DCHECK_GT(new_packet_length, 0);
432 RTC_DCHECK_EQ(old_packet_length % 10, 0);
433 RTC_DCHECK_EQ(new_packet_length % 10, 0);
434 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100435 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200436 int time_counter = 0;
437 size_t new_histogram_idx = 0;
438 for (size_t i = 0; i < histogram.size(); i++) {
439 acc += histogram[i];
440 time_counter += old_packet_length;
441 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100442 const int64_t scaled_acc = acc * new_packet_length / time_counter;
443 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200444 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100445 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
446 new_histogram[new_histogram_idx] =
447 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
448 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200449 new_histogram_idx =
450 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
451 time_counter -= new_packet_length;
452 }
453 // Only subtract the part that was succesfully written to the new histogram.
454 acc -= actually_used_acc;
455 }
456 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100457 // last bin. If we cannot add everything to the last bin we need to add as
458 // much as possible to the bins after the last bin (this is only possible
459 // when compressing a histogram).
460 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
461 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
462 new_histogram[new_histogram_idx] =
463 rtc::saturated_cast<int>(old_histogram_val + acc);
464 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
465 new_histogram_idx++;
466 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200467 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100468 if (acc == 0) {
469 // If acc is non-zero, we were not able to add everything to the new
470 // histogram, so this check will not hold.
471 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
472 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
473 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200474 return new_histogram;
475}
476
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000477bool DelayManager::SetMinimumDelay(int delay_ms) {
478 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
479 // Also, if possible check |delay| to less than 75% of
480 // |max_packets_in_buffer_|.
481 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
482 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700483 delay_ms >
484 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000485 return false;
486 }
487 minimum_delay_ms_ = delay_ms;
488 return true;
489}
490
491bool DelayManager::SetMaximumDelay(int delay_ms) {
492 if (delay_ms == 0) {
493 // Zero input unsets the maximum delay.
494 maximum_delay_ms_ = 0;
495 return true;
496 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
497 // Maximum delay shouldn't be less than minimum delay or less than a packet.
498 return false;
499 }
500 maximum_delay_ms_ = delay_ms;
501 return true;
502}
503
Yves Gerey665174f2018-06-19 15:03:05 +0200504int DelayManager::base_target_level() const {
505 return base_target_level_;
506}
507void DelayManager::set_streaming_mode(bool value) {
508 streaming_mode_ = value;
509}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000510int DelayManager::last_pack_cng_or_dtmf() const {
511 return last_pack_cng_or_dtmf_;
512}
513
514void DelayManager::set_last_pack_cng_or_dtmf(int value) {
515 last_pack_cng_or_dtmf_ = value;
516}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517} // namespace webrtc