blob: 2f7265321e0b3b3467bcbb80e0492bf939dc787b [file] [log] [blame]
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +01001/*
2 * Copyright (c) 2019 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 <algorithm>
Piasycc350322019-03-05 23:00:36 +080012#include <cstdlib>
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010013#include <numeric>
14
15#include "modules/audio_coding/neteq/histogram.h"
16#include "rtc_base/checks.h"
17#include "rtc_base/numerics/safe_conversions.h"
18
19namespace webrtc {
20
21Histogram::Histogram(size_t num_buckets, int forget_factor)
22 : buckets_(num_buckets, 0),
23 forget_factor_(0),
24 base_forget_factor_(forget_factor) {}
25
26Histogram::~Histogram() {}
27
28// Each element in the vector is first multiplied by the forgetting factor
29// |forget_factor_|. Then the vector element indicated by |iat_packets| is then
30// increased (additive) by 1 - |forget_factor_|. This way, the probability of
31// |iat_packets| is slightly increased, while the sum of the histogram remains
32// constant (=1).
33// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
34// longer sum up to 1 (in Q30) after the update. To correct this, a correction
35// term is added or subtracted from the first element (or elements) of the
36// vector.
37// The forgetting factor |forget_factor_| is also updated. When the DelayManager
38// is reset, the factor is set to 0 to facilitate rapid convergence in the
39// beginning. With each update of the histogram, the factor is increased towards
40// the steady-state value |kIatFactor_|.
41void Histogram::Add(int value) {
42 RTC_DCHECK(value >= 0);
43 RTC_DCHECK(value < static_cast<int>(buckets_.size()));
44 int vector_sum = 0; // Sum up the vector elements as they are processed.
45 // Multiply each element in |buckets_| with |forget_factor_|.
46 for (int& bucket : buckets_) {
47 bucket = (static_cast<int64_t>(bucket) * forget_factor_) >> 15;
48 vector_sum += bucket;
49 }
50
51 // Increase the probability for the currently observed inter-arrival time
52 // by 1 - |forget_factor_|. The factor is in Q15, |buckets_| in Q30.
53 // Thus, left-shift 15 steps to obtain result in Q30.
54 buckets_[value] += (32768 - forget_factor_) << 15;
55 vector_sum += (32768 - forget_factor_) << 15; // Add to vector sum.
56
57 // |buckets_| should sum up to 1 (in Q30), but it may not due to
58 // fixed-point rounding errors.
59 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
60 if (vector_sum != 0) {
61 // Modify a few values early in |buckets_|.
62 int flip_sign = vector_sum > 0 ? -1 : 1;
63 for (int& bucket : buckets_) {
64 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
Piasycc350322019-03-05 23:00:36 +080065 int correction = flip_sign * std::min(std::abs(vector_sum), bucket >> 4);
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010066 bucket += correction;
67 vector_sum += correction;
Piasycc350322019-03-05 23:00:36 +080068 if (std::abs(vector_sum) == 0) {
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010069 break;
70 }
71 }
72 }
73 RTC_DCHECK(vector_sum == 0); // Verify that the above is correct.
74
75 // Update |forget_factor_| (changes only during the first seconds after a
76 // reset). The factor converges to |base_forget_factor_|.
77 forget_factor_ += (base_forget_factor_ - forget_factor_ + 3) >> 2;
78}
79
80int Histogram::Quantile(int probability) {
81 // Find the bucket for which the probability of observing an
82 // inter-arrival time larger than or equal to |index| is larger than or
83 // equal to |probability|. The sought probability is estimated using
84 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
85 // the end up until |index|. Now, since the sum of all elements is 1
86 // (in Q30) by definition, and since the solution is often a low value for
87 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
88 // elements from the start of the histogram.
89 int inverse_probability = (1 << 30) - probability;
90 size_t index = 0; // Start from the beginning of |buckets_|.
91 int sum = 1 << 30; // Assign to 1 in Q30.
92 sum -= buckets_[index]; // Ensure that target level is >= 1.
93
94 do {
95 // Subtract the probabilities one by one until the sum is no longer greater
96 // than |inverse_probability|.
97 ++index;
98 sum -= buckets_[index];
99 } while ((sum > inverse_probability) && (index < buckets_.size() - 1));
100 return static_cast<int>(index);
101}
102
103// Set the histogram vector to an exponentially decaying distribution
104// buckets_[i] = 0.5^(i+1), i = 0, 1, 2, ...
105// buckets_ is in Q30.
106void Histogram::Reset() {
107 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
108 // of buckets_ is 1.
109 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
110 for (int& bucket : buckets_) {
111 temp_prob >>= 1;
112 bucket = temp_prob << 16;
113 }
114 forget_factor_ = 0; // Adapt the histogram faster for the first few packets.
115}
116
117int Histogram::NumBuckets() const {
118 return buckets_.size();
119}
120
121void Histogram::Scale(int old_bucket_width, int new_bucket_width) {
122 buckets_ = ScaleBuckets(buckets_, old_bucket_width, new_bucket_width);
123}
124
125std::vector<int> Histogram::ScaleBuckets(const std::vector<int>& buckets,
126 int old_bucket_width,
127 int new_bucket_width) {
128 RTC_DCHECK_GT(old_bucket_width, 0);
129 RTC_DCHECK_GT(new_bucket_width, 0);
130 RTC_DCHECK_EQ(old_bucket_width % 10, 0);
131 RTC_DCHECK_EQ(new_bucket_width % 10, 0);
132 std::vector<int> new_histogram(buckets.size(), 0);
133 int64_t acc = 0;
134 int time_counter = 0;
135 size_t new_histogram_idx = 0;
136 for (size_t i = 0; i < buckets.size(); i++) {
137 acc += buckets[i];
138 time_counter += old_bucket_width;
139 // The bins should be scaled, to ensure the histogram still sums to one.
140 const int64_t scaled_acc = acc * new_bucket_width / time_counter;
141 int64_t actually_used_acc = 0;
142 while (time_counter >= new_bucket_width) {
143 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
144 new_histogram[new_histogram_idx] =
145 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
146 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
147 new_histogram_idx =
148 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
149 time_counter -= new_bucket_width;
150 }
151 // Only subtract the part that was succesfully written to the new histogram.
152 acc -= actually_used_acc;
153 }
154 // If there is anything left in acc (due to rounding errors), add it to the
155 // last bin. If we cannot add everything to the last bin we need to add as
156 // much as possible to the bins after the last bin (this is only possible
157 // when compressing a histogram).
158 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
159 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
160 new_histogram[new_histogram_idx] =
161 rtc::saturated_cast<int>(old_histogram_val + acc);
162 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
163 new_histogram_idx++;
164 }
165 RTC_DCHECK_EQ(buckets.size(), new_histogram.size());
166 if (acc == 0) {
167 // If acc is non-zero, we were not able to add everything to the new
168 // histogram, so this check will not hold.
169 RTC_DCHECK_EQ(accumulate(buckets.begin(), buckets.end(), 0ll),
170 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
171 }
172 return new_histogram;
173}
174
175} // namespace webrtc