blob: ff65bb7eccf4c0571be4768363500052f5a045ad [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
11#include "webrtc/modules/audio_coding/neteq4/delay_manager.h"
12
13#include <assert.h>
14#include <math.h>
15
16#include <algorithm> // max, min
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
19#include "webrtc/modules/audio_coding/neteq4/delay_peak_detector.h"
20#include "webrtc/system_wrappers/interface/logging.h"
21
22namespace webrtc {
23
24DelayManager::DelayManager(int max_packets_in_buffer,
25 DelayPeakDetector* peak_detector)
26 : first_packet_received_(false),
27 max_packets_in_buffer_(max_packets_in_buffer),
28 iat_vector_(kMaxIat + 1, 0),
29 iat_factor_(0),
30 packet_iat_count_ms_(0),
31 base_target_level_(4), // In Q0 domain.
32 target_level_(base_target_level_ << 8), // In Q8 domain.
33 packet_len_ms_(0),
34 streaming_mode_(false),
35 last_seq_no_(0),
36 last_timestamp_(0),
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +000037 minimum_delay_ms_(0),
38 least_required_delay_ms_(target_level_),
39 maximum_delay_ms_(target_level_),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000040 iat_cumulative_sum_(0),
41 max_iat_cumulative_sum_(0),
42 max_timer_ms_(0),
43 peak_detector_(*peak_detector),
44 last_pack_cng_or_dtmf_(1) {
45 assert(peak_detector); // Should never be NULL.
46 Reset();
47}
48
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000049DelayManager::~DelayManager() {}
50
51const DelayManager::IATVector& DelayManager::iat_vector() const {
52 return iat_vector_;
53}
54
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000055// Set the histogram vector to an exponentially decaying distribution
56// iat_vector_[i] = 0.5^(i+1), i = 0, 1, 2, ...
57// iat_vector_ is in Q30.
58void DelayManager::ResetHistogram() {
59 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
60 // of iat_vector_ is 1.
61 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
62 IATVector::iterator it = iat_vector_.begin();
63 for (; it < iat_vector_.end(); it++) {
64 temp_prob >>= 1;
65 (*it) = temp_prob << 16;
66 }
67 base_target_level_ = 4;
68 target_level_ = base_target_level_ << 8;
69}
70
71int DelayManager::Update(uint16_t sequence_number,
72 uint32_t timestamp,
73 int sample_rate_hz) {
74 if (sample_rate_hz <= 0) {
75 return -1;
76 }
77
78 if (!first_packet_received_) {
79 // Prepare for next packet arrival.
80 packet_iat_count_ms_ = 0;
81 last_seq_no_ = sequence_number;
82 last_timestamp_ = timestamp;
83 first_packet_received_ = true;
84 return 0;
85 }
86
87 // Try calculating packet length from current and previous timestamps.
88 // TODO(hlundin): Take care of wrap-around. Not done yet due to legacy
89 // bit-exactness.
90 int packet_len_ms;
91 if ((timestamp <= last_timestamp_) || (sequence_number <= last_seq_no_)) {
92 // Wrong timestamp or sequence order; use stored value.
93 packet_len_ms = packet_len_ms_;
94 } else {
95 // Calculate timestamps per packet and derive packet length in ms.
96 int packet_len_samp =
97 static_cast<uint32_t>(timestamp - last_timestamp_) /
98 static_cast<uint16_t>(sequence_number - last_seq_no_);
99 packet_len_ms = (1000 * packet_len_samp) / sample_rate_hz;
100 }
101
102 if (packet_len_ms > 0) {
103 // Cannot update statistics unless |packet_len_ms| is valid.
104 // Calculate inter-arrival time (IAT) in integer "packet times"
105 // (rounding down). This is the value used as index to the histogram
106 // vector |iat_vector_|.
107 int iat_packets = packet_iat_count_ms_ / packet_len_ms;
108
109 if (streaming_mode_) {
110 UpdateCumulativeSums(packet_len_ms, sequence_number);
111 }
112
113 // Check for discontinuous packet sequence and re-ordering.
114 if (sequence_number > last_seq_no_ + 1) {
115 // TODO(hlundin): Take care of wrap-around. Not done yet due to legacy
116 // bit-exactness.
117 // 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.
120 iat_packets -= sequence_number - last_seq_no_ - 1;
121 iat_packets = std::max(iat_packets, 0);
122 } else if (sequence_number < last_seq_no_) {
123 // TODO(hlundin): Take care of wrap-around.
124 // Compensate for re-ordering.
125 iat_packets += last_seq_no_ + 1 - sequence_number;
126 }
127
128 // Saturate IAT at maximum value.
129 const int max_iat = kMaxIat;
130 iat_packets = std::min(iat_packets, max_iat);
131 UpdateHistogram(iat_packets);
132 // Calculate new |target_level_| based on updated statistics.
133 target_level_ = CalculateTargetLevel(iat_packets);
134 if (streaming_mode_) {
135 target_level_ = std::max(target_level_, max_iat_cumulative_sum_);
136 }
137
138 LimitTargetLevel();
139 } // End if (packet_len_ms > 0).
140
141 // Prepare for next packet arrival.
142 packet_iat_count_ms_ = 0;
143 last_seq_no_ = sequence_number;
144 last_timestamp_ = timestamp;
145 return 0;
146}
147
148void DelayManager::UpdateCumulativeSums(int packet_len_ms,
149 uint16_t sequence_number) {
150 // Calculate IAT in Q8, including fractions of a packet (i.e., more
151 // accurate than |iat_packets|.
152 int iat_packets_q8 = (packet_iat_count_ms_ << 8) / packet_len_ms;
153 // Calculate cumulative sum IAT with sequence number compensation. The sum
154 // is zero if there is no clock-drift.
155 iat_cumulative_sum_ += (iat_packets_q8 -
156 (static_cast<int>(sequence_number - last_seq_no_) << 8));
157 // Subtract drift term.
158 iat_cumulative_sum_ -= kCumulativeSumDrift;
159 // Ensure not negative.
160 iat_cumulative_sum_ = std::max(iat_cumulative_sum_, 0);
161 if (iat_cumulative_sum_ > max_iat_cumulative_sum_) {
162 // Found a new maximum.
163 max_iat_cumulative_sum_ = iat_cumulative_sum_;
164 max_timer_ms_ = 0;
165 }
166 if (max_timer_ms_ > kMaxStreamingPeakPeriodMs) {
167 // Too long since the last maximum was observed; decrease max value.
168 max_iat_cumulative_sum_ -= kCumulativeSumDrift;
169 }
170}
171
172// Each element in the vector is first multiplied by the forgetting factor
173// |iat_factor_|. Then the vector element indicated by |iat_packets| is then
174// increased (additive) by 1 - |iat_factor_|. This way, the probability of
175// |iat_packets| is slightly increased, while the sum of the histogram remains
176// constant (=1).
177// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
178// longer sum up to 1 (in Q30) after the update. To correct this, a correction
179// term is added or subtracted from the first element (or elements) of the
180// vector.
181// The forgetting factor |iat_factor_| is also updated. When the DelayManager
182// is reset, the factor is set to 0 to facilitate rapid convergence in the
183// beginning. With each update of the histogram, the factor is increased towards
184// the steady-state value |kIatFactor_|.
185void DelayManager::UpdateHistogram(size_t iat_packets) {
186 assert(iat_packets < iat_vector_.size());
187 int vector_sum = 0; // Sum up the vector elements as they are processed.
188 // Multiply each element in |iat_vector_| with |iat_factor_|.
189 for (IATVector::iterator it = iat_vector_.begin();
190 it != iat_vector_.end(); ++it) {
191 *it = (static_cast<int64_t>(*it) * iat_factor_) >> 15;
192 vector_sum += *it;
193 }
194
195 // Increase the probability for the currently observed inter-arrival time
196 // by 1 - |iat_factor_|. The factor is in Q15, |iat_vector_| in Q30.
197 // Thus, left-shift 15 steps to obtain result in Q30.
198 iat_vector_[iat_packets] += (32768 - iat_factor_) << 15;
199 vector_sum += (32768 - iat_factor_) << 15; // Add to vector sum.
200
201 // |iat_vector_| should sum up to 1 (in Q30), but it may not due to
202 // fixed-point rounding errors.
203 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
204 if (vector_sum != 0) {
205 // Modify a few values early in |iat_vector_|.
206 int flip_sign = vector_sum > 0 ? -1 : 1;
207 IATVector::iterator it = iat_vector_.begin();
208 while (it != iat_vector_.end() && abs(vector_sum) > 0) {
209 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
210 int correction = flip_sign * std::min(abs(vector_sum), (*it) >> 4);
211 *it += correction;
212 vector_sum += correction;
213 ++it;
214 }
215 }
216 assert(vector_sum == 0); // Verify that the above is correct.
217
218 // Update |iat_factor_| (changes only during the first seconds after a reset).
219 // The factor converges to |kIatFactor_|.
220 iat_factor_ += (kIatFactor_ - iat_factor_ + 3) >> 2;
221}
222
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000223// Enforces upper and lower limits for |target_level_|. The upper limit is
224// chosen to be minimum of i) 75% of |max_packets_in_buffer_|, to leave some
225// headroom for natural fluctuations around the target, and ii) equivalent of
226// |maximum_delay_ms_| in packets. Note that in practice, if no
227// |maximum_delay_ms_| is specified, this does not have any impact, since the
228// target level is far below the buffer capacity in all reasonable cases.
229// The lower limit is equivalent of |minimum_delay_ms_| in packets. We update
230// |least_required_level_| while the above limits are applied.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000231// TODO(hlundin): Move this check to the buffer logistics class.
232void DelayManager::LimitTargetLevel() {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000233 least_required_delay_ms_ = (target_level_ * packet_len_ms_) >> 8;
234
235 if (packet_len_ms_ > 0 && minimum_delay_ms_ > 0) {
236 int minimum_delay_packet_q8 = (minimum_delay_ms_ << 8) / packet_len_ms_;
237 target_level_ = std::max(target_level_, minimum_delay_packet_q8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000238 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000239
240 if (maximum_delay_ms_ > 0 && packet_len_ms_ > 0) {
241 int maximum_delay_packet_q8 = (maximum_delay_ms_ << 8) / packet_len_ms_;
242 target_level_ = std::min(target_level_, maximum_delay_packet_q8);
243 }
244
245 // Shift to Q8, then 75%.;
246 int max_buffer_packets_q8 = (3 * (max_packets_in_buffer_ << 8)) / 4;
247 target_level_ = std::min(target_level_, max_buffer_packets_q8);
248
249 // Sanity check, at least 1 packet (in Q8).
250 target_level_ = std::max(target_level_, 1 << 8);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000251}
252
253int DelayManager::CalculateTargetLevel(int iat_packets) {
254 int limit_probability = kLimitProbability;
255 if (streaming_mode_) {
256 limit_probability = kLimitProbabilityStreaming;
257 }
258
259 // Calculate target buffer level from inter-arrival time histogram.
260 // Find the |iat_index| for which the probability of observing an
261 // inter-arrival time larger than or equal to |iat_index| is less than or
262 // equal to |limit_probability|. The sought probability is estimated using
263 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
264 // the end up until |iat_index|. Now, since the sum of all elements is 1
265 // (in Q30) by definition, and since the solution is often a low value for
266 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
267 // elements from the start of the histogram.
268 size_t index = 0; // Start from the beginning of |iat_vector_|.
269 int sum = 1 << 30; // Assign to 1 in Q30.
270 sum -= iat_vector_[index]; // Ensure that target level is >= 1.
271
272 do {
273 // Subtract the probabilities one by one until the sum is no longer greater
274 // than limit_probability.
275 ++index;
276 sum -= iat_vector_[index];
277 } while ((sum > limit_probability) && (index < iat_vector_.size() - 1));
278
279 // This is the base value for the target buffer level.
280 int target_level = index;
281 base_target_level_ = index;
282
283 // Update detector for delay peaks.
284 bool delay_peak_found = peak_detector_.Update(iat_packets, target_level);
285 if (delay_peak_found) {
286 target_level = std::max(static_cast<int>(target_level),
287 peak_detector_.MaxPeakHeight());
288 }
289
290 // Sanity check. |target_level| must be strictly positive.
291 target_level = std::max(target_level, 1);
292 // Scale to Q8 and assign to member variable.
293 target_level_ = target_level << 8;
294 return target_level_;
295}
296
297int DelayManager::SetPacketAudioLength(int length_ms) {
298 if (length_ms <= 0) {
299 LOG_F(LS_ERROR) << "length_ms = " << length_ms;
300 return -1;
301 }
302 packet_len_ms_ = length_ms;
303 peak_detector_.SetPacketAudioLength(packet_len_ms_);
304 packet_iat_count_ms_ = 0;
305 last_pack_cng_or_dtmf_ = 1; // TODO(hlundin): Legacy. Remove?
306 return 0;
307}
308
309
310void DelayManager::Reset() {
311 packet_len_ms_ = 0; // Packet size unknown.
312 streaming_mode_ = false;
313 peak_detector_.Reset();
314 ResetHistogram(); // Resets target levels too.
315 iat_factor_ = 0; // Adapt the histogram faster for the first few packets.
316 packet_iat_count_ms_ = 0;
317 max_timer_ms_ = 0;
318 iat_cumulative_sum_ = 0;
319 max_iat_cumulative_sum_ = 0;
320 last_pack_cng_or_dtmf_ = 1;
321}
322
323int DelayManager::AverageIAT() const {
324 int32_t sum_q24 = 0;
325 assert(iat_vector_.size() == 65); // Algorithm is hard-coded for this size.
326 for (size_t i = 0; i < iat_vector_.size(); ++i) {
327 // Shift 6 to fit worst case: 2^30 * 64.
328 sum_q24 += (iat_vector_[i] >> 6) * i;
329 }
330 // Subtract the nominal inter-arrival time 1 = 2^24 in Q24.
331 sum_q24 -= (1 << 24);
332 // Multiply with 1000000 / 2^24 = 15625 / 2^18 to get in parts-per-million.
333 // Shift 7 to Q17 first, then multiply with 15625 and shift another 11.
334 return ((sum_q24 >> 7) * 15625) >> 11;
335}
336
337bool DelayManager::PeakFound() const {
338 return peak_detector_.peak_found();
339}
340
341void DelayManager::UpdateCounters(int elapsed_time_ms) {
342 packet_iat_count_ms_ += elapsed_time_ms;
343 peak_detector_.IncrementCounter(elapsed_time_ms);
344 max_timer_ms_ += elapsed_time_ms;
345}
346
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000347void DelayManager::ResetPacketIatCount() { packet_iat_count_ms_ = 0; }
348
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000349// Note that |low_limit| and |higher_limit| are not assigned to
350// |minimum_delay_ms_| and |maximum_delay_ms_| defined by the client of this
351// class. They are computed from |target_level_| and used for decision making.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352void DelayManager::BufferLimits(int* lower_limit, int* higher_limit) const {
353 if (!lower_limit || !higher_limit) {
354 LOG_F(LS_ERROR) << "NULL pointers supplied as input";
355 assert(false);
356 return;
357 }
358
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 int window_20ms = 0x7FFF; // Default large value for legacy bit-exactness.
360 if (packet_len_ms_ > 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361 window_20ms = (20 << 8) / packet_len_ms_;
362 }
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000363
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 // |target_level_| is in Q8 already.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000365 *lower_limit = (target_level_ * 3) / 4;
366 // |higher_limit| is equal to |target_level_|, but should at
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 // least be 20 ms higher than |lower_limit_|.
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000368 *higher_limit = std::max(target_level_, *lower_limit + window_20ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369}
370
371int DelayManager::TargetLevel() const {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000372 return target_level_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373}
374
375void DelayManager::LastDecoderType(NetEqDecoder decoder_type) {
376 if (decoder_type == kDecoderAVT ||
377 decoder_type == kDecoderCNGnb ||
378 decoder_type == kDecoderCNGwb ||
379 decoder_type == kDecoderCNGswb32kHz ||
380 decoder_type == kDecoderCNGswb48kHz) {
381 last_pack_cng_or_dtmf_ = 1;
382 } else if (last_pack_cng_or_dtmf_ != 0) {
383 last_pack_cng_or_dtmf_ = -1;
384 }
385}
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000386
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000387bool DelayManager::SetMinimumDelay(int delay_ms) {
388 // Minimum delay shouldn't be more than maximum delay, if any maximum is set.
389 // Also, if possible check |delay| to less than 75% of
390 // |max_packets_in_buffer_|.
391 if ((maximum_delay_ms_ > 0 && delay_ms > maximum_delay_ms_) ||
392 (packet_len_ms_ > 0 &&
393 delay_ms > 3 * max_packets_in_buffer_ * packet_len_ms_ / 4)) {
394 return false;
395 }
396 minimum_delay_ms_ = delay_ms;
397 return true;
398}
399
400bool DelayManager::SetMaximumDelay(int delay_ms) {
401 if (delay_ms == 0) {
402 // Zero input unsets the maximum delay.
403 maximum_delay_ms_ = 0;
404 return true;
405 } else if (delay_ms < minimum_delay_ms_ || delay_ms < packet_len_ms_) {
406 // Maximum delay shouldn't be less than minimum delay or less than a packet.
407 return false;
408 }
409 maximum_delay_ms_ = delay_ms;
410 return true;
411}
412
413int DelayManager::least_required_delay_ms() const {
414 return least_required_delay_ms_;
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +0000415}
416
417int DelayManager::base_target_level() const { return base_target_level_; }
418void DelayManager::set_streaming_mode(bool value) { streaming_mode_ = value; }
419int DelayManager::last_pack_cng_or_dtmf() const {
420 return last_pack_cng_or_dtmf_;
421}
422
423void DelayManager::set_last_pack_cng_or_dtmf(int value) {
424 last_pack_cng_or_dtmf_ = value;
425}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000426} // namespace webrtc