blob: 628812a251d592555b177f62f690958ff1c2555d [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,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070065 DelayPeakDetector* peak_detector,
66 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000067 : first_packet_received_(false),
68 max_packets_in_buffer_(max_packets_in_buffer),
69 iat_vector_(kMaxIat + 1, 0),
70 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070071 tick_timer_(tick_timer),
Ivo Creusen385b10b2017-10-13 12:37:27 +020072 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000073 target_level_(base_target_level_ << 8), // In Q8 domain.
74 packet_len_ms_(0),
75 streaming_mode_(false),
76 last_seq_no_(0),
77 last_timestamp_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000078 minimum_delay_ms_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000079 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 iat_cumulative_sum_(0),
81 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020083 last_pack_cng_or_dtmf_(1),
84 frame_length_change_experiment_(
Minyue Li002fbb82018-10-04 11:31:03 +020085 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")),
86 forced_limit_probability_(GetForcedLimitProbability()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000087 assert(peak_detector); // Should never be NULL.
Minyue Li002fbb82018-10-04 11:31:03 +020088
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 Reset();
90}
91
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000092DelayManager::~DelayManager() {}
93
94const DelayManager::IATVector& DelayManager::iat_vector() const {
95 return iat_vector_;
96}
97
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098// Set the histogram vector to an exponentially decaying distribution
99// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
100// iat_vector_ is in Q30.
101void DelayManager::ResetHistogram() {
102 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
103 // of iat_vector_ is 1.
104 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
105 IATVector::iterator it = iat_vector_.begin();
106 for (; it < iat_vector_.end(); it++) {
107 temp_prob >>= 1;
108 (*it) = temp_prob << 16;
109 }
110 base_target_level_ = 4;
111 target_level_ = base_target_level_ << 8;
112}
113
114int DelayManager::Update(uint16_t sequence_number,
115 uint32_t timestamp,
116 int sample_rate_hz) {
117 if (sample_rate_hz <= 0) {
118 return -1;
119 }
120
121 if (!first_packet_received_) {
122 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700123 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 last_seq_no_ = sequence_number;
125 last_timestamp_ = timestamp;
126 first_packet_received_ = true;
127 return 0;
128 }
129
130 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000132 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
133 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 // Wrong timestamp or sequence order; use stored value.
135 packet_len_ms = packet_len_ms_;
136 } else {
137 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800138 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000139 static_cast<uint32_t>(timestamp - last_timestamp_) /
140 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800141 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700142 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000143 }
144
145 if (packet_len_ms > 0) {
146 // Cannot update statistics unless |packet_len_ms| is valid.
147 // Calculate inter-arrival time (IAT) in integer "packet times"
148 // (rounding down). This is the value used as index to the histogram
149 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700150 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151
152 if (streaming_mode_) {
153 UpdateCumulativeSums(packet_len_ms, sequence_number);
154 }
155
156 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000157 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158 // Compensate for gap in the sequence numbers. Reduce IAT with the
159 // expected extra time due to lost packets, but ensure that the IAT is
160 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000161 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000162 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000163 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
164 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 }
166
167 // Saturate IAT at maximum value.
168 const int max_iat = kMaxIat;
169 iat_packets = std::min(iat_packets, max_iat);
170 UpdateHistogram(iat_packets);
171 // Calculate new |target_level_| based on updated statistics.
172 target_level_ = CalculateTargetLevel(iat_packets);
173 if (streaming_mode_) {
174 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
175 }
176
177 LimitTargetLevel();
178 } // End if (packet_len_ms > 0).
179
180 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700181 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 last_seq_no_ = sequence_number;
183 last_timestamp_ = timestamp;
184 return 0;
185}
186
187void DelayManager::UpdateCumulativeSums(int packet_len_ms,
188 uint16_t sequence_number) {
189 // Calculate IAT in Q8, including fractions of a packet (i.e., more
190 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700191 int iat_packets_q8 =
192 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000193 // Calculate cumulative sum IAT with sequence number compensation. The sum
194 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200195 iat_cumulative_sum_ +=
196 (iat_packets_q8 -
197 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000198 // Subtract drift term.
199 iat_cumulative_sum_ -= kCumulativeSumDrift;
200 // Ensure not negative.
201 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
202 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
203 // Found a new maximum.
204 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700205 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000206 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700207 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 // Too long since the last maximum was observed; decrease max value.
209 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
210 }
211}
212
213// Each element in the vector is first multiplied by the forgetting factor
214// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
215// increased (additive) by 1 - |iat_factor_|. This way, the probability of
216// |iat_packets| is slightly increased, while the sum of the histogram remains
217// constant (=1).
218// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
219// longer sum up to 1 (in Q30) after the update. To correct this, a correction
220// term is added or subtracted from the first element (or elements) of the
221// vector.
222// The forgetting factor |iat_factor_| is also updated. When the DelayManager
223// is reset, the factor is set to 0 to facilitate rapid convergence in the
224// beginning. With each update of the histogram, the factor is increased towards
225// the steady-state value |kIatFactor_|.
226void DelayManager::UpdateHistogram(size_t iat_packets) {
227 assert(iat_packets < iat_vector_.size());
228 int vector_sum = 0; // Sum up the vector elements as they are processed.
229 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200230 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
231 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000232 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
233 vector_sum += *it;
234 }
235
236 // Increase the probability for the currently observed inter-arrival time
237 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
238 // Thus, left-shift 15 steps to obtain result in Q30.
239 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
240 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
241
242 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
243 // fixed-point rounding errors.
244 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
245 if (vector_sum != 0) {
246 // Modify a few values early in |iat_vector_|.
247 int flip_sign = vector_sum > 0 ? -1 : 1;
248 IATVector::iterator it = iat_vector_.begin();
249 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
250 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
251 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
252 *it += correction;
253 vector_sum += correction;
254 ++it;
255 }
256 }
257 assert(vector_sum == 0); // Verify that the above is correct.
258
259 // Update |iat_factor_| (changes only during the first seconds after a reset).
260 // The factor converges to |kIatFactor_|.
261 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
262}
263
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264// Enforces upper and lower limits for |target_level_|. The upper limit is
265// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
266// headroom for natural fluctuations around the target, and ii) equivalent of
267// |maximum_delay_ms_| in packets. Note that in practice, if no
268// |maximum_delay_ms_| is specified, this does not have any impact, since the
269// target level is far below the buffer capacity in all reasonable cases.
270// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
271// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000272// TODO(hlundin): Move this check to the buffer logistics class.
273void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000274 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200275 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000276 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000277 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000278
279 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
280 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
281 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
282 }
283
284 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700285 int max_buffer_packets_q8 =
286 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000287 target_level_ = std::min(target_level_, max_buffer_packets_q8);
288
289 // Sanity check, at least 1 packet (in Q8).
290 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291}
292
293int DelayManager::CalculateTargetLevel(int iat_packets) {
Minyue Li002fbb82018-10-04 11:31:03 +0200294 int limit_probability = forced_limit_probability_.value_or(kLimitProbability);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295 if (streaming_mode_) {
296 limit_probability = kLimitProbabilityStreaming;
297 }
298
299 // Calculate target buffer level from inter-arrival time histogram.
300 // Find the |iat_index| for which the probability of observing an
301 // inter-arrival time larger than or equal to |iat_index| is less than or
302 // equal to |limit_probability|. The sought probability is estimated using
303 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
304 // the end up until |iat_index|. Now, since the sum of all elements is 1
305 // (in Q30) by definition, and since the solution is often a low value for
306 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
307 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200308 size_t index = 0; // Start from the beginning of |iat_vector_|.
309 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
311
312 do {
313 // Subtract the probabilities one by one until the sum is no longer greater
314 // than limit_probability.
315 ++index;
316 sum -= iat_vector_[index];
317 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
318
319 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000320 int target_level = static_cast<int>(index);
321 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322
323 // Update detector for delay peaks.
324 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
325 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000326 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 }
328
329 // Sanity check. |target_level| must be strictly positive.
330 target_level = std::max(target_level, 1);
331 // Scale to Q8 and assign to member variable.
332 target_level_ = target_level << 8;
333 return target_level_;
334}
335
336int DelayManager::SetPacketAudioLength(int length_ms) {
337 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100338 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000339 return -1;
340 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200341 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
342 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
343 }
344
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000345 packet_len_ms_ = length_ms;
346 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700347 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000348 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
349 return 0;
350}
351
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352void DelayManager::Reset() {
353 packet_len_ms_ = 0; // Packet size unknown.
354 streaming_mode_ = false;
355 peak_detector_.Reset();
356 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200357 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700358 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
359 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360 iat_cumulative_sum_ = 0;
361 max_iat_cumulative_sum_ = 0;
362 last_pack_cng_or_dtmf_ = 1;
363}
364
henrik.lundin0d838572016-10-13 03:35:55 -0700365double DelayManager::EstimatedClockDriftPpm() const {
366 double sum = 0.0;
367 // Calculate the expected value based on the probabilities in |iat_vector_|.
368 for (size_t i = 0; i < iat_vector_.size(); ++i) {
369 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370 }
henrik.lundin0d838572016-10-13 03:35:55 -0700371 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
372 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
373 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
374 // (ppm).
375 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376}
377
378bool DelayManager::PeakFound() const {
379 return peak_detector_.peak_found();
380}
381
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700382void DelayManager::ResetPacketIatCount() {
383 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384}
385
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000386// Note that |low_limit| and |higher_limit| are not assigned to
387// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
388// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000389void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
390 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100391 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392 assert(false);
393 return;
394 }
395
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000396 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
397 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398 window_20ms = (20 << 8) / packet_len_ms_;
399 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000400
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000402 *lower_limit = (target_level_ * 3) / 4;
403 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000405 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000406}
407
408int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000409 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000410}
411
ossuf1b08da2016-09-23 02:19:43 -0700412void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
413 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000414 last_pack_cng_or_dtmf_ = 1;
415 } else if (last_pack_cng_or_dtmf_ != 0) {
416 last_pack_cng_or_dtmf_ = -1;
417 }
418}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000419
henrik.lundinb8c55b12017-05-10 07:38:01 -0700420void DelayManager::RegisterEmptyPacket() {
421 ++last_seq_no_;
422}
423
Ivo Creusen385b10b2017-10-13 12:37:27 +0200424DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
425 int old_packet_length,
426 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200427 if (old_packet_length == 0) {
428 // If we don't know the previous frame length, don't make any changes to the
429 // histogram.
430 return histogram;
431 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200432 RTC_DCHECK_GT(new_packet_length, 0);
433 RTC_DCHECK_EQ(old_packet_length % 10, 0);
434 RTC_DCHECK_EQ(new_packet_length % 10, 0);
435 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100436 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200437 int time_counter = 0;
438 size_t new_histogram_idx = 0;
439 for (size_t i = 0; i < histogram.size(); i++) {
440 acc += histogram[i];
441 time_counter += old_packet_length;
442 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100443 const int64_t scaled_acc = acc * new_packet_length / time_counter;
444 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200445 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100446 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
447 new_histogram[new_histogram_idx] =
448 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
449 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200450 new_histogram_idx =
451 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
452 time_counter -= new_packet_length;
453 }
454 // Only subtract the part that was succesfully written to the new histogram.
455 acc -= actually_used_acc;
456 }
457 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100458 // last bin. If we cannot add everything to the last bin we need to add as
459 // much as possible to the bins after the last bin (this is only possible
460 // when compressing a histogram).
461 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
462 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
463 new_histogram[new_histogram_idx] =
464 rtc::saturated_cast<int>(old_histogram_val + acc);
465 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
466 new_histogram_idx++;
467 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200468 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100469 if (acc == 0) {
470 // If acc is non-zero, we were not able to add everything to the new
471 // histogram, so this check will not hold.
472 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
473 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
474 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200475 return new_histogram;
476}
477
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000478bool DelayManager::SetMinimumDelay(int delay_ms) {
479 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
480 // Also, if possible check |delay| to less than 75% of
481 // |max_packets_in_buffer_|.
482 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
483 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700484 delay_ms >
485 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000486 return false;
487 }
488 minimum_delay_ms_ = delay_ms;
489 return true;
490}
491
492bool DelayManager::SetMaximumDelay(int delay_ms) {
493 if (delay_ms == 0) {
494 // Zero input unsets the maximum delay.
495 maximum_delay_ms_ = 0;
496 return true;
497 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
498 // Maximum delay shouldn't be less than minimum delay or less than a packet.
499 return false;
500 }
501 maximum_delay_ms_ = delay_ms;
502 return true;
503}
504
Yves Gerey665174f2018-06-19 15:03:05 +0200505int DelayManager::base_target_level() const {
506 return base_target_level_;
507}
508void DelayManager::set_streaming_mode(bool value) {
509 streaming_mode_ = value;
510}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000511int DelayManager::last_pack_cng_or_dtmf() const {
512 return last_pack_cng_or_dtmf_;
513}
514
515void DelayManager::set_last_pack_cng_or_dtmf(int value) {
516 last_pack_cng_or_dtmf_ = value;
517}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000518} // namespace webrtc