blob: 84d457c6a0613c8f232d72bc6f851aee1795edf1 [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),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000043 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000044 iat_cumulative_sum_(0),
45 max_iat_cumulative_sum_(0),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000046 peak_detector_(*peak_detector),
Ivo Creusen385b10b2017-10-13 12:37:27 +020047 last_pack_cng_or_dtmf_(1),
48 frame_length_change_experiment_(
49 field_trial::IsEnabled("WebRTC-Audio-NetEqFramelengthExperiment")) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000050 assert(peak_detector); // Should never be NULL.
51 Reset();
52}
53
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000054DelayManager::~DelayManager() {}
55
56const DelayManager::IATVector& DelayManager::iat_vector() const {
57 return iat_vector_;
58}
59
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000060// Set the histogram vector to an exponentially decaying distribution
61// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
62// iat_vector_ is in Q30.
63void DelayManager::ResetHistogram() {
64 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
65 // of iat_vector_ is 1.
66 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
67 IATVector::iterator it = iat_vector_.begin();
68 for (; it < iat_vector_.end(); it++) {
69 temp_prob >>= 1;
70 (*it) = temp_prob << 16;
71 }
72 base_target_level_ = 4;
73 target_level_ = base_target_level_ << 8;
74}
75
76int DelayManager::Update(uint16_t sequence_number,
77 uint32_t timestamp,
78 int sample_rate_hz) {
79 if (sample_rate_hz <= 0) {
80 return -1;
81 }
82
83 if (!first_packet_received_) {
84 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -070085 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000086 last_seq_no_ = sequence_number;
87 last_timestamp_ = timestamp;
88 first_packet_received_ = true;
89 return 0;
90 }
91
92 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +000094 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
95 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 // Wrong timestamp or sequence order; use stored value.
97 packet_len_ms = packet_len_ms_;
98 } else {
99 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -0800100 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101 static_cast<uint32_t>(timestamp - last_timestamp_) /
102 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800103 packet_len_ms =
henrik.lundin38d840c2016-08-18 03:49:32 -0700104 rtc::saturated_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000105 }
106
107 if (packet_len_ms > 0) {
108 // Cannot update statistics unless |packet_len_ms| is valid.
109 // Calculate inter-arrival time (IAT) in integer "packet times"
110 // (rounding down). This is the value used as index to the histogram
111 // vector |iat_vector_|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700112 int iat_packets = packet_iat_stopwatch_->ElapsedMs() / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000113
114 if (streaming_mode_) {
115 UpdateCumulativeSums(packet_len_ms, sequence_number);
116 }
117
118 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000119 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120 // Compensate for gap in the sequence numbers. Reduce IAT with the
121 // expected extra time due to lost packets, but ensure that the IAT is
122 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000123 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000125 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
126 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000127 }
128
129 // Saturate IAT at maximum value.
130 const int max_iat = kMaxIat;
131 iat_packets = std::min(iat_packets, max_iat);
132 UpdateHistogram(iat_packets);
133 // Calculate new |target_level_| based on updated statistics.
134 target_level_ = CalculateTargetLevel(iat_packets);
135 if (streaming_mode_) {
136 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
137 }
138
139 LimitTargetLevel();
140 } // End if (packet_len_ms > 0).
141
142 // Prepare for next packet arrival.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700143 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000144 last_seq_no_ = sequence_number;
145 last_timestamp_ = timestamp;
146 return 0;
147}
148
149void DelayManager::UpdateCumulativeSums(int packet_len_ms,
150 uint16_t sequence_number) {
151 // Calculate IAT in Q8, including fractions of a packet (i.e., more
152 // accurate than |iat_packets|.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700153 int iat_packets_q8 =
154 (packet_iat_stopwatch_->ElapsedMs() << 8) / packet_len_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000155 // Calculate cumulative sum IAT with sequence number compensation. The sum
156 // is zero if there is no clock-drift.
Yves Gerey665174f2018-06-19 15:03:05 +0200157 iat_cumulative_sum_ +=
158 (iat_packets_q8 -
159 (static_cast<int>(sequence_number - last_seq_no_) << 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160 // Subtract drift term.
161 iat_cumulative_sum_ -= kCumulativeSumDrift;
162 // Ensure not negative.
163 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
164 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
165 // Found a new maximum.
166 max_iat_cumulative_sum_ = iat_cumulative_sum_;
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700167 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 }
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700169 if (max_iat_stopwatch_->ElapsedMs() > kMaxStreamingPeakPeriodMs) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000170 // Too long since the last maximum was observed; decrease max value.
171 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
172 }
173}
174
175// Each element in the vector is first multiplied by the forgetting factor
176// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
177// increased (additive) by 1 - |iat_factor_|. This way, the probability of
178// |iat_packets| is slightly increased, while the sum of the histogram remains
179// constant (=1).
180// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
181// longer sum up to 1 (in Q30) after the update. To correct this, a correction
182// term is added or subtracted from the first element (or elements) of the
183// vector.
184// The forgetting factor |iat_factor_| is also updated. When the DelayManager
185// is reset, the factor is set to 0 to facilitate rapid convergence in the
186// beginning. With each update of the histogram, the factor is increased towards
187// the steady-state value |kIatFactor_|.
188void DelayManager::UpdateHistogram(size_t iat_packets) {
189 assert(iat_packets < iat_vector_.size());
190 int vector_sum = 0; // Sum up the vector elements as they are processed.
191 // Multiply each element in |iat_vector_| with |iat_factor_|.
Yves Gerey665174f2018-06-19 15:03:05 +0200192 for (IATVector::iterator it = iat_vector_.begin(); it != iat_vector_.end();
193 ++it) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000194 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
195 vector_sum += *it;
196 }
197
198 // Increase the probability for the currently observed inter-arrival time
199 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
200 // Thus, left-shift 15 steps to obtain result in Q30.
201 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
202 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
203
204 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
205 // fixed-point rounding errors.
206 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
207 if (vector_sum != 0) {
208 // Modify a few values early in |iat_vector_|.
209 int flip_sign = vector_sum > 0 ? -1 : 1;
210 IATVector::iterator it = iat_vector_.begin();
211 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
212 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
213 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
214 *it += correction;
215 vector_sum += correction;
216 ++it;
217 }
218 }
219 assert(vector_sum == 0); // Verify that the above is correct.
220
221 // Update |iat_factor_| (changes only during the first seconds after a reset).
222 // The factor converges to |kIatFactor_|.
223 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
224}
225
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000226// Enforces upper and lower limits for |target_level_|. The upper limit is
227// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
228// headroom for natural fluctuations around the target, and ii) equivalent of
229// |maximum_delay_ms_| in packets. Note that in practice, if no
230// |maximum_delay_ms_| is specified, this does not have any impact, since the
231// target level is far below the buffer capacity in all reasonable cases.
232// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
233// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000234// TODO(hlundin): Move this check to the buffer logistics class.
235void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000236 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +0200237 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000238 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000239 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000240
241 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
242 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
243 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
244 }
245
246 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700247 int max_buffer_packets_q8 =
248 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000249 target_level_ = std::min(target_level_, max_buffer_packets_q8);
250
251 // Sanity check, at least 1 packet (in Q8).
252 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253}
254
255int DelayManager::CalculateTargetLevel(int iat_packets) {
256 int limit_probability = kLimitProbability;
257 if (streaming_mode_) {
258 limit_probability = kLimitProbabilityStreaming;
259 }
260
261 // Calculate target buffer level from inter-arrival time histogram.
262 // Find the |iat_index| for which the probability of observing an
263 // inter-arrival time larger than or equal to |iat_index| is less than or
264 // equal to |limit_probability|. The sought probability is estimated using
265 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
266 // the end up until |iat_index|. Now, since the sum of all elements is 1
267 // (in Q30) by definition, and since the solution is often a low value for
268 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
269 // elements from the start of the histogram.
Yves Gerey665174f2018-06-19 15:03:05 +0200270 size_t index = 0; // Start from the beginning of |iat_vector_|.
271 int sum = 1 << 30; // Assign to 1 in Q30.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000272 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
273
274 do {
275 // Subtract the probabilities one by one until the sum is no longer greater
276 // than limit_probability.
277 ++index;
278 sum -= iat_vector_[index];
279 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
280
281 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000282 int target_level = static_cast<int>(index);
283 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284
285 // Update detector for delay peaks.
286 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
287 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000288 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 }
290
291 // Sanity check. |target_level| must be strictly positive.
292 target_level = std::max(target_level, 1);
293 // Scale to Q8 and assign to member variable.
294 target_level_ = target_level << 8;
295 return target_level_;
296}
297
298int DelayManager::SetPacketAudioLength(int length_ms) {
299 if (length_ms <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100300 RTC_LOG_F(LS_ERROR) << "length_ms = " << length_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 return -1;
302 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200303 if (frame_length_change_experiment_ && packet_len_ms_ != length_ms) {
304 iat_vector_ = ScaleHistogram(iat_vector_, packet_len_ms_, length_ms);
305 }
306
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000307 packet_len_ms_ = length_ms;
308 peak_detector_.SetPacketAudioLength(packet_len_ms_);
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700309 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
311 return 0;
312}
313
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314void DelayManager::Reset() {
315 packet_len_ms_ = 0; // Packet size unknown.
316 streaming_mode_ = false;
317 peak_detector_.Reset();
318 ResetHistogram(); // Resets target levels too.
Yves Gerey665174f2018-06-19 15:03:05 +0200319 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700320 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
321 max_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 iat_cumulative_sum_ = 0;
323 max_iat_cumulative_sum_ = 0;
324 last_pack_cng_or_dtmf_ = 1;
325}
326
henrik.lundin0d838572016-10-13 03:35:55 -0700327double DelayManager::EstimatedClockDriftPpm() const {
328 double sum = 0.0;
329 // Calculate the expected value based on the probabilities in |iat_vector_|.
330 for (size_t i = 0; i < iat_vector_.size(); ++i) {
331 sum += static_cast<double>(iat_vector_[i]) * i;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000332 }
henrik.lundin0d838572016-10-13 03:35:55 -0700333 // The probabilities in |iat_vector_| are in Q30. Divide by 1 << 30 to convert
334 // to Q0; subtract the nominal inter-arrival time (1) to make a zero
335 // clockdrift represent as 0; mulitply by 1000000 to produce parts-per-million
336 // (ppm).
337 return (sum / (1 << 30) - 1) * 1e6;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000338}
339
340bool DelayManager::PeakFound() const {
341 return peak_detector_.peak_found();
342}
343
henrik.lundin8f8c96d2016-04-28 23:19:20 -0700344void DelayManager::ResetPacketIatCount() {
345 packet_iat_stopwatch_ = tick_timer_->GetNewStopwatch();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346}
347
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000348// Note that |low_limit| and |higher_limit| are not assigned to
349// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
350// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
352 if (!lower_limit || !higher_limit) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100353 RTC_LOG_F(LS_ERROR) << "NULL pointers supplied as input";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 assert(false);
355 return;
356 }
357
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000358 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
359 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360 window_20ms = (20 << 8) / packet_len_ms_;
361 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000362
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000364 *lower_limit = (target_level_ * 3) / 4;
365 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000367 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368}
369
370int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000371 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372}
373
ossuf1b08da2016-09-23 02:19:43 -0700374void DelayManager::LastDecodedWasCngOrDtmf(bool it_was) {
375 if (it_was) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376 last_pack_cng_or_dtmf_ = 1;
377 } else if (last_pack_cng_or_dtmf_ != 0) {
378 last_pack_cng_or_dtmf_ = -1;
379 }
380}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000381
henrik.lundinb8c55b12017-05-10 07:38:01 -0700382void DelayManager::RegisterEmptyPacket() {
383 ++last_seq_no_;
384}
385
Ivo Creusen385b10b2017-10-13 12:37:27 +0200386DelayManager::IATVector DelayManager::ScaleHistogram(const IATVector& histogram,
387 int old_packet_length,
388 int new_packet_length) {
Ivo Creusen25eb28c2017-10-17 17:19:14 +0200389 if (old_packet_length == 0) {
390 // If we don't know the previous frame length, don't make any changes to the
391 // histogram.
392 return histogram;
393 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200394 RTC_DCHECK_GT(new_packet_length, 0);
395 RTC_DCHECK_EQ(old_packet_length % 10, 0);
396 RTC_DCHECK_EQ(new_packet_length % 10, 0);
397 IATVector new_histogram(histogram.size(), 0);
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100398 int64_t acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200399 int time_counter = 0;
400 size_t new_histogram_idx = 0;
401 for (size_t i = 0; i < histogram.size(); i++) {
402 acc += histogram[i];
403 time_counter += old_packet_length;
404 // The bins should be scaled, to ensure the histogram still sums to one.
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100405 const int64_t scaled_acc = acc * new_packet_length / time_counter;
406 int64_t actually_used_acc = 0;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200407 while (time_counter >= new_packet_length) {
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100408 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
409 new_histogram[new_histogram_idx] =
410 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
411 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
Ivo Creusen385b10b2017-10-13 12:37:27 +0200412 new_histogram_idx =
413 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
414 time_counter -= new_packet_length;
415 }
416 // Only subtract the part that was succesfully written to the new histogram.
417 acc -= actually_used_acc;
418 }
419 // If there is anything left in acc (due to rounding errors), add it to the
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100420 // last bin. If we cannot add everything to the last bin we need to add as
421 // much as possible to the bins after the last bin (this is only possible
422 // when compressing a histogram).
423 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
424 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
425 new_histogram[new_histogram_idx] =
426 rtc::saturated_cast<int>(old_histogram_val + acc);
427 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
428 new_histogram_idx++;
429 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200430 RTC_DCHECK_EQ(histogram.size(), new_histogram.size());
Ivo Creusend95a7dd2017-12-11 16:47:48 +0100431 if (acc == 0) {
432 // If acc is non-zero, we were not able to add everything to the new
433 // histogram, so this check will not hold.
434 RTC_DCHECK_EQ(accumulate(histogram.begin(), histogram.end(), 0ll),
435 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
436 }
Ivo Creusen385b10b2017-10-13 12:37:27 +0200437 return new_histogram;
438}
439
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000440bool DelayManager::SetMinimumDelay(int delay_ms) {
441 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
442 // Also, if possible check |delay| to less than 75% of
443 // |max_packets_in_buffer_|.
444 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
445 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700446 delay_ms >
447 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000448 return false;
449 }
450 minimum_delay_ms_ = delay_ms;
451 return true;
452}
453
454bool DelayManager::SetMaximumDelay(int delay_ms) {
455 if (delay_ms == 0) {
456 // Zero input unsets the maximum delay.
457 maximum_delay_ms_ = 0;
458 return true;
459 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
460 // Maximum delay shouldn't be less than minimum delay or less than a packet.
461 return false;
462 }
463 maximum_delay_ms_ = delay_ms;
464 return true;
465}
466
Yves Gerey665174f2018-06-19 15:03:05 +0200467int DelayManager::base_target_level() const {
468 return base_target_level_;
469}
470void DelayManager::set_streaming_mode(bool value) {
471 streaming_mode_ = value;
472}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000473int DelayManager::last_pack_cng_or_dtmf() const {
474 return last_pack_cng_or_dtmf_;
475}
476
477void DelayManager::set_last_pack_cng_or_dtmf(int value) {
478 last_pack_cng_or_dtmf_ = value;
479}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480} // namespace webrtc