blob: af49f00f8af0be85d31da95933085e55110241c6 [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
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/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
17
henrik.lundin07c51e32016-02-11 03:35:43 -080018#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000020#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010021#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010022#include "webrtc/system_wrappers/include/logging.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000023
24namespace webrtc {
25
Peter Kastingdce40cf2015-08-24 14:52:23 -070026DelayManager::DelayManager(size_t max_packets_in_buffer,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000027 DelayPeakDetector* peak_detector)
28 : first_packet_received_(false),
29 max_packets_in_buffer_(max_packets_in_buffer),
30 iat_vector_(kMaxIat + 1, 0),
31 iat_factor_(0),
32 packet_iat_count_ms_(0),
33 base_target_level_(4), // In Q0 domain.
34 target_level_(base_target_level_ << 8), // In Q8 domain.
35 packet_len_ms_(0),
36 streaming_mode_(false),
37 last_seq_no_(0),
38 last_timestamp_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000039 minimum_delay_ms_(0),
40 least_required_delay_ms_(target_level_),
41 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000042 iat_cumulative_sum_(0),
43 max_iat_cumulative_sum_(0),
44 max_timer_ms_(0),
45 peak_detector_(*peak_detector),
46 last_pack_cng_or_dtmf_(1) {
47 assert(peak_detector); // Should never be NULL.
48 Reset();
49}
50
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000051DelayManager::~DelayManager() {}
52
53const DelayManager::IATVector& DelayManager::iat_vector() const {
54 return iat_vector_;
55}
56
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000057// Set the histogram vector to an exponentially decaying distribution
58// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
59// iat_vector_ is in Q30.
60void DelayManager::ResetHistogram() {
61 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
62 // of iat_vector_ is 1.
63 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
64 IATVector::iterator it = iat_vector_.begin();
65 for (; it < iat_vector_.end(); it++) {
66 temp_prob >>= 1;
67 (*it) = temp_prob << 16;
68 }
69 base_target_level_ = 4;
70 target_level_ = base_target_level_ << 8;
71}
72
73int DelayManager::Update(uint16_t sequence_number,
74 uint32_t timestamp,
75 int sample_rate_hz) {
76 if (sample_rate_hz <= 0) {
77 return -1;
78 }
79
80 if (!first_packet_received_) {
81 // Prepare for next packet arrival.
82 packet_iat_count_ms_ = 0;
83 last_seq_no_ = sequence_number;
84 last_timestamp_ = timestamp;
85 first_packet_received_ = true;
86 return 0;
87 }
88
89 // Try calculating packet length from current and previous timestamps.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 int packet_len_ms;
turaj@webrtc.org78b41a02013-11-22 20:27:07 +000091 if (!IsNewerTimestamp(timestamp, last_timestamp_) ||
92 !IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 // Wrong timestamp or sequence order; use stored value.
94 packet_len_ms = packet_len_ms_;
95 } else {
96 // Calculate timestamps per packet and derive packet length in ms.
henrik.lundin07c51e32016-02-11 03:35:43 -080097 int64_t packet_len_samp =
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 static_cast<uint32_t>(timestamp - last_timestamp_) /
99 static_cast<uint16_t>(sequence_number - last_seq_no_);
henrik.lundin07c51e32016-02-11 03:35:43 -0800100 packet_len_ms =
101 rtc::checked_cast<int>(1000 * packet_len_samp / sample_rate_hz);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 }
103
104 if (packet_len_ms > 0) {
105 // Cannot update statistics unless |packet_len_ms| is valid.
106 // Calculate inter-arrival time (IAT) in integer "packet times"
107 // (rounding down). This is the value used as index to the histogram
108 // vector |iat_vector_|.
109 int iat_packets = packet_iat_count_ms_ / packet_len_ms;
110
111 if (streaming_mode_) {
112 UpdateCumulativeSums(packet_len_ms, sequence_number);
113 }
114
115 // Check for discontinuous packet sequence and re-ordering.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000116 if (IsNewerSequenceNumber(sequence_number, last_seq_no_ + 1)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 // Compensate for gap in the sequence numbers. Reduce IAT with the
118 // expected extra time due to lost packets, but ensure that the IAT is
119 // not negative.
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000120 iat_packets -= static_cast<uint16_t>(sequence_number - last_seq_no_ - 1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 iat_packets = std::max(iat_packets, 0);
turaj@webrtc.org78b41a02013-11-22 20:27:07 +0000122 } else if (!IsNewerSequenceNumber(sequence_number, last_seq_no_)) {
123 iat_packets += static_cast<uint16_t>(last_seq_no_ + 1 - sequence_number);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 }
125
126 // Saturate IAT at maximum value.
127 const int max_iat = kMaxIat;
128 iat_packets = std::min(iat_packets, max_iat);
129 UpdateHistogram(iat_packets);
130 // Calculate new |target_level_| based on updated statistics.
131 target_level_ = CalculateTargetLevel(iat_packets);
132 if (streaming_mode_) {
133 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
134 }
135
136 LimitTargetLevel();
137 } // End if (packet_len_ms > 0).
138
139 // Prepare for next packet arrival.
140 packet_iat_count_ms_ = 0;
141 last_seq_no_ = sequence_number;
142 last_timestamp_ = timestamp;
143 return 0;
144}
145
146void DelayManager::UpdateCumulativeSums(int packet_len_ms,
147 uint16_t sequence_number) {
148 // Calculate IAT in Q8, including fractions of a packet (i.e., more
149 // accurate than |iat_packets|.
150 int iat_packets_q8 = (packet_iat_count_ms_ << 8) / packet_len_ms;
151 // Calculate cumulative sum IAT with sequence number compensation. The sum
152 // is zero if there is no clock-drift.
153 iat_cumulative_sum_ += (iat_packets_q8 -
154 (static_cast<int>(sequence_number - last_seq_no_) << 8));
155 // Subtract drift term.
156 iat_cumulative_sum_ -= kCumulativeSumDrift;
157 // Ensure not negative.
158 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
159 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
160 // Found a new maximum.
161 max_iat_cumulative_sum_ = iat_cumulative_sum_;
162 max_timer_ms_ = 0;
163 }
164 if (max_timer_ms_ > kMaxStreamingPeakPeriodMs) {
165 // Too long since the last maximum was observed; decrease max value.
166 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
167 }
168}
169
170// Each element in the vector is first multiplied by the forgetting factor
171// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
172// increased (additive) by 1 - |iat_factor_|. This way, the probability of
173// |iat_packets| is slightly increased, while the sum of the histogram remains
174// constant (=1).
175// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
176// longer sum up to 1 (in Q30) after the update. To correct this, a correction
177// term is added or subtracted from the first element (or elements) of the
178// vector.
179// The forgetting factor |iat_factor_| is also updated. When the DelayManager
180// is reset, the factor is set to 0 to facilitate rapid convergence in the
181// beginning. With each update of the histogram, the factor is increased towards
182// the steady-state value |kIatFactor_|.
183void DelayManager::UpdateHistogram(size_t iat_packets) {
184 assert(iat_packets < iat_vector_.size());
185 int vector_sum = 0; // Sum up the vector elements as they are processed.
186 // Multiply each element in |iat_vector_| with |iat_factor_|.
187 for (IATVector::iterator it = iat_vector_.begin();
188 it != iat_vector_.end(); ++it) {
189 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
190 vector_sum += *it;
191 }
192
193 // Increase the probability for the currently observed inter-arrival time
194 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
195 // Thus, left-shift 15 steps to obtain result in Q30.
196 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
197 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
198
199 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
200 // fixed-point rounding errors.
201 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
202 if (vector_sum != 0) {
203 // Modify a few values early in |iat_vector_|.
204 int flip_sign = vector_sum > 0 ? -1 : 1;
205 IATVector::iterator it = iat_vector_.begin();
206 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
207 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
208 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
209 *it += correction;
210 vector_sum += correction;
211 ++it;
212 }
213 }
214 assert(vector_sum == 0); // Verify that the above is correct.
215
216 // Update |iat_factor_| (changes only during the first seconds after a reset).
217 // The factor converges to |kIatFactor_|.
218 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
219}
220
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000221// Enforces upper and lower limits for |target_level_|. The upper limit is
222// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
223// headroom for natural fluctuations around the target, and ii) equivalent of
224// |maximum_delay_ms_| in packets. Note that in practice, if no
225// |maximum_delay_ms_| is specified, this does not have any impact, since the
226// target level is far below the buffer capacity in all reasonable cases.
227// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
228// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000229// TODO(hlundin): Move this check to the buffer logistics class.
230void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000231 least_required_delay_ms_ = (target_level_ * packet_len_ms_) >> 8;
232
233 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
234 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
235 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000236 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000237
238 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
239 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
240 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
241 }
242
243 // Shift to Q8, then 75%.;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700244 int max_buffer_packets_q8 =
245 static_cast<int>((3 * (max_packets_in_buffer_ << 8)) / 4);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000246 target_level_ = std::min(target_level_, max_buffer_packets_q8);
247
248 // Sanity check, at least 1 packet (in Q8).
249 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250}
251
252int DelayManager::CalculateTargetLevel(int iat_packets) {
253 int limit_probability = kLimitProbability;
254 if (streaming_mode_) {
255 limit_probability = kLimitProbabilityStreaming;
256 }
257
258 // Calculate target buffer level from inter-arrival time histogram.
259 // Find the |iat_index| for which the probability of observing an
260 // inter-arrival time larger than or equal to |iat_index| is less than or
261 // equal to |limit_probability|. The sought probability is estimated using
262 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
263 // the end up until |iat_index|. Now, since the sum of all elements is 1
264 // (in Q30) by definition, and since the solution is often a low value for
265 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
266 // elements from the start of the histogram.
267 size_t index = 0; // Start from the beginning of |iat_vector_|.
268 int sum = 1 << 30; // Assign to 1 in Q30.
269 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
270
271 do {
272 // Subtract the probabilities one by one until the sum is no longer greater
273 // than limit_probability.
274 ++index;
275 sum -= iat_vector_[index];
276 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
277
278 // This is the base value for the target buffer level.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000279 int target_level = static_cast<int>(index);
280 base_target_level_ = static_cast<int>(index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000281
282 // Update detector for delay peaks.
283 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
284 if (delay_peak_found) {
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000285 target_level = std::max(target_level, peak_detector_.MaxPeakHeight());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 }
287
288 // Sanity check. |target_level| must be strictly positive.
289 target_level = std::max(target_level, 1);
290 // Scale to Q8 and assign to member variable.
291 target_level_ = target_level << 8;
292 return target_level_;
293}
294
295int DelayManager::SetPacketAudioLength(int length_ms) {
296 if (length_ms <= 0) {
297 LOG_F(LS_ERROR) << "length_ms = " << length_ms;
298 return -1;
299 }
300 packet_len_ms_ = length_ms;
301 peak_detector_.SetPacketAudioLength(packet_len_ms_);
302 packet_iat_count_ms_ = 0;
303 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
304 return 0;
305}
306
307
308void DelayManager::Reset() {
309 packet_len_ms_ = 0; // Packet size unknown.
310 streaming_mode_ = false;
311 peak_detector_.Reset();
312 ResetHistogram(); // Resets target levels too.
313 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
314 packet_iat_count_ms_ = 0;
315 max_timer_ms_ = 0;
316 iat_cumulative_sum_ = 0;
317 max_iat_cumulative_sum_ = 0;
318 last_pack_cng_or_dtmf_ = 1;
319}
320
321int DelayManager::AverageIAT() const {
322 int32_t sum_q24 = 0;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000323 // Using an int for the upper limit of the following for-loop so the
324 // loop-counter can be int. Otherwise we need a cast where |sum_q24| is
325 // updated.
326 const int iat_vec_size = static_cast<int>(iat_vector_.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 assert(iat_vector_.size() == 65); // Algorithm is hard-coded for this size.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000328 for (int i = 0; i < iat_vec_size; ++i) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 // Shift 6 to fit worst case: 2^30 * 64.
330 sum_q24 += (iat_vector_[i] >> 6) * i;
331 }
332 // Subtract the nominal inter-arrival time 1 = 2^24 in Q24.
333 sum_q24 -= (1 << 24);
334 // Multiply with 1000000 / 2^24 = 15625 / 2^18 to get in parts-per-million.
335 // Shift 7 to Q17 first, then multiply with 15625 and shift another 11.
336 return ((sum_q24 >> 7) * 15625) >> 11;
337}
338
339bool DelayManager::PeakFound() const {
340 return peak_detector_.peak_found();
341}
342
343void DelayManager::UpdateCounters(int elapsed_time_ms) {
344 packet_iat_count_ms_ += elapsed_time_ms;
345 peak_detector_.IncrementCounter(elapsed_time_ms);
346 max_timer_ms_ += elapsed_time_ms;
347}
348
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000349void DelayManager::ResetPacketIatCount() { packet_iat_count_ms_ = 0; }
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) {
356 LOG_F(LS_ERROR) << "NULL pointers supplied as input";
357 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
377void DelayManager::LastDecoderType(NetEqDecoder decoder_type) {
kwibergee1879c2015-10-29 06:20:28 -0700378 if (decoder_type == NetEqDecoder::kDecoderAVT ||
379 decoder_type == NetEqDecoder::kDecoderCNGnb ||
380 decoder_type == NetEqDecoder::kDecoderCNGwb ||
381 decoder_type == NetEqDecoder::kDecoderCNGswb32kHz ||
382 decoder_type == NetEqDecoder::kDecoderCNGswb48kHz) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 last_pack_cng_or_dtmf_ = 1;
384 } else if (last_pack_cng_or_dtmf_ != 0) {
385 last_pack_cng_or_dtmf_ = -1;
386 }
387}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000388
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000389bool DelayManager::SetMinimumDelay(int delay_ms) {
390 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
391 // Also, if possible check |delay| to less than 75% of
392 // |max_packets_in_buffer_|.
393 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
394 (packet_len_ms_ > 0 &&
Peter Kastingdce40cf2015-08-24 14:52:23 -0700395 delay_ms >
396 static_cast<int>(3 * max_packets_in_buffer_ * packet_len_ms_ / 4))) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000397 return false;
398 }
399 minimum_delay_ms_ = delay_ms;
400 return true;
401}
402
403bool DelayManager::SetMaximumDelay(int delay_ms) {
404 if (delay_ms == 0) {
405 // Zero input unsets the maximum delay.
406 maximum_delay_ms_ = 0;
407 return true;
408 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
409 // Maximum delay shouldn't be less than minimum delay or less than a packet.
410 return false;
411 }
412 maximum_delay_ms_ = delay_ms;
413 return true;
414}
415
416int DelayManager::least_required_delay_ms() const {
417 return least_required_delay_ms_;
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000418}
419
420int DelayManager::base_target_level() const { return base_target_level_; }
421void DelayManager::set_streaming_mode(bool value) { streaming_mode_ = value; }
422int DelayManager::last_pack_cng_or_dtmf() const {
423 return last_pack_cng_or_dtmf_;
424}
425
426void DelayManager::set_last_pack_cng_or_dtmf(int value) {
427 last_pack_cng_or_dtmf_ = value;
428}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429} // namespace webrtc