blob: a945cdcad844ce0d25a42c65af188703b1454a51 [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
26namespace webrtc {
27
Peter Kastingdce40cf2015-08-24 14:52:23 -070028DelayManager::DelayManager(size_t max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070029 DelayPeakDetector* peak_detector,
30 const TickTimer* tick_timer)
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000031 : first_packet_received_(false),
32 max_packets_in_buffer_(max_packets_in_buffer),
33 iat_vector_(kMaxIat + 1, 0),
34 iat_factor_(0),
henrik.lundin8f8c96d2016-04-28 23:19:20 -070035 tick_timer_(tick_timer),
Ivo Creusen385b10b2017-10-13 12:37:27 +020036 base_target_level_(4), // In Q0 domain.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000037 target_level_(base_target_level_ << 8), // In Q8 domain.
38 packet_len_ms_(0),
39 streaming_mode_(false),
40 last_seq_no_(0),
41 last_timestamp_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000042 minimum_delay_ms_(0),
43 least_required_delay_ms_(target_level_),
44 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000045 iat_cumulative_sum_(0),
46 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000047 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020048 last_pack_cng_or_dtmf_(1),
49 frame_length_change_experiment_(
50 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051 assert(peak_detector); // Should never be NULL.
52 Reset();
53}
54
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000055DelayManager::~DelayManager() {}
56
57const DelayManager::IATVector& DelayManager::iat_vector() const {
58 return iat_vector_;
59}
60
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000061// Set the histogram vector to an exponentially decaying distribution
62// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
63// iat_vector_ is in Q30.
64void DelayManager::ResetHistogram() {
65 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
66 // of iat_vector_ is 1.
67 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
68 IATVector::iterator it = iat_vector_.begin();
69 for (; it < iat_vector_.end(); it++) {
70 temp_prob >>= 1;
71 (*it) = temp_prob << 16;
72 }
73 base_target_level_ = 4;
74 target_level_ = base_target_level_ << 8;
75}
76
77int DelayManager::Update(uint16_t sequence_number,
78 uint32_t timestamp,
79 int sample_rate_hz) {
80 if (sample_rate_hz <= 0) {
81 return -1;
82 }
83
84 if (!first_packet_received_) {
85 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -070086 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000087 last_seq_no_ = sequence_number;
88 last_timestamp_ = timestamp;
89 first_packet_received_ = true;
90 return 0;
91 }
92
93 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +000095 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
96 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 // Wrong timestamp or sequence order; use stored value.
98 packet_len_ms = packet_len_ms_;
99 } else {
100 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800101 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 static_cast<uint32_t>(timestamp - last_timestamp_) /
103 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800104 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700105 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 }
107
108 if (packet_len_ms > 0) {
109 // Cannot update statistics unless |packet_len_ms| is valid.
110 // Calculate inter-arrival time (IAT) in integer "packet times"
111 // (rounding down). This is the value used as index to the histogram
112 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700113 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114
115 if (streaming_mode_) {
116 UpdateCumulativeSums(packet_len_ms, sequence_number);
117 }
118
119 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000120 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 // Compensate for gap in the sequence numbers. Reduce IAT with the
122 // expected extra time due to lost packets, but ensure that the IAT is
123 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000124 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000126 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
127 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 }
129
130 // Saturate IAT at maximum value.
131 const int max_iat = kMaxIat;
132 iat_packets = std::min(iat_packets, max_iat);
133 UpdateHistogram(iat_packets);
134 // Calculate new |target_level_| based on updated statistics.
135 target_level_ = CalculateTargetLevel(iat_packets);
136 if (streaming_mode_) {
137 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
138 }
139
140 LimitTargetLevel();
141 } // End if (packet_len_ms > 0).
142
143 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700144 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000145 last_seq_no_ = sequence_number;
146 last_timestamp_ = timestamp;
147 return 0;
148}
149
150void DelayManager::UpdateCumulativeSums(int packet_len_ms,
151 uint16_t sequence_number) {
152 // Calculate IAT in Q8, including fractions of a packet (i.e., more
153 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700154 int iat_packets_q8 =
155 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000156 // Calculate cumulative sum IAT with sequence number compensation. The sum
157 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200158 iat_cumulative_sum_ +=
159 (iat_packets_q8 -
160 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000161 // Subtract drift term.
162 iat_cumulative_sum_ -= kCumulativeSumDrift;
163 // Ensure not negative.
164 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
165 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
166 // Found a new maximum.
167 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700168 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000169 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700170 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 // Too long since the last maximum was observed; decrease max value.
172 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
173 }
174}
175
176// Each element in the vector is first multiplied by the forgetting factor
177// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
178// increased (additive) by 1 - |iat_factor_|. This way, the probability of
179// |iat_packets| is slightly increased, while the sum of the histogram remains
180// constant (=1).
181// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
182// longer sum up to 1 (in Q30) after the update. To correct this, a correction
183// term is added or subtracted from the first element (or elements) of the
184// vector.
185// The forgetting factor |iat_factor_| is also updated. When the DelayManager
186// is reset, the factor is set to 0 to facilitate rapid convergence in the
187// beginning. With each update of the histogram, the factor is increased towards
188// the steady-state value |kIatFactor_|.
189void DelayManager::UpdateHistogram(size_t iat_packets) {
190 assert(iat_packets < iat_vector_.size());
191 int vector_sum = 0; // Sum up the vector elements as they are processed.
192 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200193 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
194 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000195 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
196 vector_sum += *it;
197 }
198
199 // Increase the probability for the currently observed inter-arrival time
200 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
201 // Thus, left-shift 15 steps to obtain result in Q30.
202 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
203 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
204
205 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
206 // fixed-point rounding errors.
207 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
208 if (vector_sum != 0) {
209 // Modify a few values early in |iat_vector_|.
210 int flip_sign = vector_sum > 0 ? -1 : 1;
211 IATVector::iterator it = iat_vector_.begin();
212 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
213 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
214 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
215 *it += correction;
216 vector_sum += correction;
217 ++it;
218 }
219 }
220 assert(vector_sum == 0); // Verify that the above is correct.
221
222 // Update |iat_factor_| (changes only during the first seconds after a reset).
223 // The factor converges to |kIatFactor_|.
224 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
225}
226
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000227// Enforces upper and lower limits for |target_level_|. The upper limit is
228// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
229// headroom for natural fluctuations around the target, and ii) equivalent of
230// |maximum_delay_ms_| in packets. Note that in practice, if no
231// |maximum_delay_ms_| is specified, this does not have any impact, since the
232// target level is far below the buffer capacity in all reasonable cases.
233// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
234// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000235// TODO(hlundin): Move this check to the buffer logistics class.
236void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000237 least_required_delay_ms_ = (target_level_ * packet_len_ms_) >> 8;
238
239 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200240 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000241 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000242 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000243
244 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
245 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
246 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
247 }
248
249 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700250 int max_buffer_packets_q8 =
251 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000252 target_level_ = std::min(target_level_, max_buffer_packets_q8);
253
254 // Sanity check, at least 1 packet (in Q8).
255 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256}
257
258int DelayManager::CalculateTargetLevel(int iat_packets) {
259 int limit_probability = kLimitProbability;
260 if (streaming_mode_) {
261 limit_probability = kLimitProbabilityStreaming;
262 }
263
264 // Calculate target buffer level from inter-arrival time histogram.
265 // Find the |iat_index| for which the probability of observing an
266 // inter-arrival time larger than or equal to |iat_index| is less than or
267 // equal to |limit_probability|. The sought probability is estimated using
268 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
269 // the end up until |iat_index|. Now, since the sum of all elements is 1
270 // (in Q30) by definition, and since the solution is often a low value for
271 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
272 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200273 size_t index = 0; // Start from the beginning of |iat_vector_|.
274 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
276
277 do {
278 // Subtract the probabilities one by one until the sum is no longer greater
279 // than limit_probability.
280 ++index;
281 sum -= iat_vector_[index];
282 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
283
284 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000285 int target_level = static_cast<int>(index);
286 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287
288 // Update detector for delay peaks.
289 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
290 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000291 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000292 }
293
294 // Sanity check. |target_level| must be strictly positive.
295 target_level = std::max(target_level, 1);
296 // Scale to Q8 and assign to member variable.
297 target_level_ = target_level << 8;
298 return target_level_;
299}
300
301int DelayManager::SetPacketAudioLength(int length_ms) {
302 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100303 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 return -1;
305 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200306 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
307 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
308 }
309
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 packet_len_ms_ = length_ms;
311 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700312 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000313 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
314 return 0;
315}
316
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317void DelayManager::Reset() {
318 packet_len_ms_ = 0; // Packet size unknown.
319 streaming_mode_ = false;
320 peak_detector_.Reset();
321 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200322 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700323 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
324 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000325 iat_cumulative_sum_ = 0;
326 max_iat_cumulative_sum_ = 0;
327 last_pack_cng_or_dtmf_ = 1;
328}
329
henrik.lundin0d838572016-10-13 03:35:55 -0700330double DelayManager::EstimatedClockDriftPpm() const {
331 double sum = 0.0;
332 // Calculate the expected value based on the probabilities in |iat_vector_|.
333 for (size_t i = 0; i < iat_vector_.size(); ++i) {
334 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335 }
henrik.lundin0d838572016-10-13 03:35:55 -0700336 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
337 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
338 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
339 // (ppm).
340 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341}
342
343bool DelayManager::PeakFound() const {
344 return peak_detector_.peak_found();
345}
346
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700347void DelayManager::ResetPacketIatCount() {
348 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349}
350
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000351// Note that |low_limit| and |higher_limit| are not assigned to
352// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
353// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
355 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100356 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 assert(false);
358 return;
359 }
360
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
362 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363 window_20ms = (20 << 8) / packet_len_ms_;
364 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000365
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000367 *lower_limit = (target_level_ * 3) / 4;
368 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000370 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371}
372
373int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000374 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000375}
376
ossuf1b08da2016-09-23 02:19:43 -0700377void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
378 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379 last_pack_cng_or_dtmf_ = 1;
380 } else if (last_pack_cng_or_dtmf_ != 0) {
381 last_pack_cng_or_dtmf_ = -1;
382 }
383}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000384
henrik.lundinb8c55b12017-05-10 07:38:01 -0700385void DelayManager::RegisterEmptyPacket() {
386 ++last_seq_no_;
387}
388
Ivo Creusen385b10b2017-10-13 12:37:27 +0200389DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
390 int old_packet_length,
391 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200392 if (old_packet_length == 0) {
393 // If we don't know the previous frame length, don't make any changes to the
394 // histogram.
395 return histogram;
396 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200397 RTC_DCHECK_GT(new_packet_length, 0);
398 RTC_DCHECK_EQ(old_packet_length % 10, 0);
399 RTC_DCHECK_EQ(new_packet_length % 10, 0);
400 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100401 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200402 int time_counter = 0;
403 size_t new_histogram_idx = 0;
404 for (size_t i = 0; i < histogram.size(); i++) {
405 acc += histogram[i];
406 time_counter += old_packet_length;
407 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100408 const int64_t scaled_acc = acc * new_packet_length / time_counter;
409 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200410 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100411 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
412 new_histogram[new_histogram_idx] =
413 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
414 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200415 new_histogram_idx =
416 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
417 time_counter -= new_packet_length;
418 }
419 // Only subtract the part that was succesfully written to the new histogram.
420 acc -= actually_used_acc;
421 }
422 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100423 // last bin. If we cannot add everything to the last bin we need to add as
424 // much as possible to the bins after the last bin (this is only possible
425 // when compressing a histogram).
426 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
427 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
428 new_histogram[new_histogram_idx] =
429 rtc::saturated_cast<int>(old_histogram_val + acc);
430 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
431 new_histogram_idx++;
432 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200433 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100434 if (acc == 0) {
435 // If acc is non-zero, we were not able to add everything to the new
436 // histogram, so this check will not hold.
437 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
438 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
439 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200440 return new_histogram;
441}
442
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000443bool DelayManager::SetMinimumDelay(int delay_ms) {
444 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
445 // Also, if possible check |delay| to less than 75% of
446 // |max_packets_in_buffer_|.
447 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
448 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700449 delay_ms >
450 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000451 return false;
452 }
453 minimum_delay_ms_ = delay_ms;
454 return true;
455}
456
457bool DelayManager::SetMaximumDelay(int delay_ms) {
458 if (delay_ms == 0) {
459 // Zero input unsets the maximum delay.
460 maximum_delay_ms_ = 0;
461 return true;
462 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
463 // Maximum delay shouldn't be less than minimum delay or less than a packet.
464 return false;
465 }
466 maximum_delay_ms_ = delay_ms;
467 return true;
468}
469
470int DelayManager::least_required_delay_ms() const {
471 return least_required_delay_ms_;
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000472}
473
Yves Gerey665174f2018-06-19 15:03:05 +0200474int DelayManager::base_target_level() const {
475 return base_target_level_;
476}
477void DelayManager::set_streaming_mode(bool value) {
478 streaming_mode_ = value;
479}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000480int DelayManager::last_pack_cng_or_dtmf() const {
481 return last_pack_cng_or_dtmf_;
482}
483
484void DelayManager::set_last_pack_cng_or_dtmf(int value) {
485 last_pack_cng_or_dtmf_ = value;
486}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487} // namespace webrtc