blob: fc0801e482d7107324acc7f2b17967dd0a3ce46f [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
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020015#include "absl/types/optional.h"
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010016#include "modules/audio_coding/neteq/histogram.h"
17#include "rtc_base/checks.h"
18#include "rtc_base/numerics/safe_conversions.h"
19
20namespace webrtc {
21
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020022Histogram::Histogram(size_t num_buckets,
23 int forget_factor,
24 absl::optional<double> start_forget_weight)
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010025 : buckets_(num_buckets, 0),
26 forget_factor_(0),
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020027 base_forget_factor_(forget_factor),
28 add_count_(0),
29 start_forget_weight_(start_forget_weight) {
30 RTC_DCHECK_LT(base_forget_factor_, 1 << 15);
31}
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010032
33Histogram::~Histogram() {}
34
35// Each element in the vector is first multiplied by the forgetting factor
36// |forget_factor_|. Then the vector element indicated by |iat_packets| is then
37// increased (additive) by 1 - |forget_factor_|. This way, the probability of
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020038// |value| is slightly increased, while the sum of the histogram remains
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010039// constant (=1).
40// Due to inaccuracies in the fixed-point arithmetic, the histogram may no
41// longer sum up to 1 (in Q30) after the update. To correct this, a correction
42// term is added or subtracted from the first element (or elements) of the
43// vector.
44// The forgetting factor |forget_factor_| is also updated. When the DelayManager
45// is reset, the factor is set to 0 to facilitate rapid convergence in the
46// beginning. With each update of the histogram, the factor is increased towards
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020047// the steady-state value |base_forget_factor_|.
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010048void Histogram::Add(int value) {
49 RTC_DCHECK(value >= 0);
50 RTC_DCHECK(value < static_cast<int>(buckets_.size()));
51 int vector_sum = 0; // Sum up the vector elements as they are processed.
52 // Multiply each element in |buckets_| with |forget_factor_|.
53 for (int& bucket : buckets_) {
54 bucket = (static_cast<int64_t>(bucket) * forget_factor_) >> 15;
55 vector_sum += bucket;
56 }
57
58 // Increase the probability for the currently observed inter-arrival time
59 // by 1 - |forget_factor_|. The factor is in Q15, |buckets_| in Q30.
60 // Thus, left-shift 15 steps to obtain result in Q30.
61 buckets_[value] += (32768 - forget_factor_) << 15;
62 vector_sum += (32768 - forget_factor_) << 15; // Add to vector sum.
63
64 // |buckets_| should sum up to 1 (in Q30), but it may not due to
65 // fixed-point rounding errors.
66 vector_sum -= 1 << 30; // Should be zero. Compensate if not.
67 if (vector_sum != 0) {
68 // Modify a few values early in |buckets_|.
69 int flip_sign = vector_sum > 0 ? -1 : 1;
70 for (int& bucket : buckets_) {
71 // Add/subtract 1/16 of the element, but not more than |vector_sum|.
Piasycc350322019-03-05 23:00:36 +080072 int correction = flip_sign * std::min(std::abs(vector_sum), bucket >> 4);
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010073 bucket += correction;
74 vector_sum += correction;
Piasycc350322019-03-05 23:00:36 +080075 if (std::abs(vector_sum) == 0) {
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010076 break;
77 }
78 }
79 }
80 RTC_DCHECK(vector_sum == 0); // Verify that the above is correct.
81
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020082 ++add_count_;
83
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +010084 // Update |forget_factor_| (changes only during the first seconds after a
85 // reset). The factor converges to |base_forget_factor_|.
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +020086 if (start_forget_weight_) {
87 if (forget_factor_ != base_forget_factor_) {
88 int old_forget_factor = forget_factor_;
89 int forget_factor =
90 (1 << 15) * (1 - start_forget_weight_.value() / (add_count_ + 1));
91 forget_factor_ =
92 std::max(0, std::min(base_forget_factor_, forget_factor));
93 // The histogram is updated recursively by forgetting the old histogram
94 // with |forget_factor_| and adding a new sample multiplied by |1 -
95 // forget_factor_|. We need to make sure that the effective weight on the
96 // new sample is no smaller than those on the old samples, i.e., to
97 // satisfy the following DCHECK.
98 RTC_DCHECK_GE((1 << 15) - forget_factor_,
99 ((1 << 15) - old_forget_factor) * forget_factor_ >> 15);
100 }
101 } else {
102 forget_factor_ += (base_forget_factor_ - forget_factor_ + 3) >> 2;
103 }
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100104}
105
106int Histogram::Quantile(int probability) {
107 // Find the bucket for which the probability of observing an
108 // inter-arrival time larger than or equal to |index| is larger than or
109 // equal to |probability|. The sought probability is estimated using
110 // the histogram as the reverse cumulant PDF, i.e., the sum of elements from
111 // the end up until |index|. Now, since the sum of all elements is 1
112 // (in Q30) by definition, and since the solution is often a low value for
113 // |iat_index|, it is more efficient to start with |sum| = 1 and subtract
114 // elements from the start of the histogram.
115 int inverse_probability = (1 << 30) - probability;
116 size_t index = 0; // Start from the beginning of |buckets_|.
117 int sum = 1 << 30; // Assign to 1 in Q30.
118 sum -= buckets_[index]; // Ensure that target level is >= 1.
119
120 do {
121 // Subtract the probabilities one by one until the sum is no longer greater
122 // than |inverse_probability|.
123 ++index;
124 sum -= buckets_[index];
125 } while ((sum > inverse_probability) && (index < buckets_.size() - 1));
126 return static_cast<int>(index);
127}
128
129// Set the histogram vector to an exponentially decaying distribution
130// buckets_[i] = 0.5^(i+1), i = 0, 1, 2, ...
131// buckets_ is in Q30.
132void Histogram::Reset() {
133 // Set temp_prob to (slightly more than) 1 in Q14. This ensures that the sum
134 // of buckets_ is 1.
135 uint16_t temp_prob = 0x4002; // 16384 + 2 = 100000000000010 binary.
136 for (int& bucket : buckets_) {
137 temp_prob >>= 1;
138 bucket = temp_prob << 16;
139 }
140 forget_factor_ = 0; // Adapt the histogram faster for the first few packets.
Jakob Ivarssone9a2ee22019-05-22 16:54:09 +0200141 add_count_ = 0;
Jakob Ivarsson1eb3d7e2019-02-21 15:42:31 +0100142}
143
144int Histogram::NumBuckets() const {
145 return buckets_.size();
146}
147
148void Histogram::Scale(int old_bucket_width, int new_bucket_width) {
149 buckets_ = ScaleBuckets(buckets_, old_bucket_width, new_bucket_width);
150}
151
152std::vector<int> Histogram::ScaleBuckets(const std::vector<int>& buckets,
153 int old_bucket_width,
154 int new_bucket_width) {
155 RTC_DCHECK_GT(old_bucket_width, 0);
156 RTC_DCHECK_GT(new_bucket_width, 0);
157 RTC_DCHECK_EQ(old_bucket_width % 10, 0);
158 RTC_DCHECK_EQ(new_bucket_width % 10, 0);
159 std::vector<int> new_histogram(buckets.size(), 0);
160 int64_t acc = 0;
161 int time_counter = 0;
162 size_t new_histogram_idx = 0;
163 for (size_t i = 0; i < buckets.size(); i++) {
164 acc += buckets[i];
165 time_counter += old_bucket_width;
166 // The bins should be scaled, to ensure the histogram still sums to one.
167 const int64_t scaled_acc = acc * new_bucket_width / time_counter;
168 int64_t actually_used_acc = 0;
169 while (time_counter >= new_bucket_width) {
170 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
171 new_histogram[new_histogram_idx] =
172 rtc::saturated_cast<int>(old_histogram_val + scaled_acc);
173 actually_used_acc += new_histogram[new_histogram_idx] - old_histogram_val;
174 new_histogram_idx =
175 std::min(new_histogram_idx + 1, new_histogram.size() - 1);
176 time_counter -= new_bucket_width;
177 }
178 // Only subtract the part that was succesfully written to the new histogram.
179 acc -= actually_used_acc;
180 }
181 // If there is anything left in acc (due to rounding errors), add it to the
182 // last bin. If we cannot add everything to the last bin we need to add as
183 // much as possible to the bins after the last bin (this is only possible
184 // when compressing a histogram).
185 while (acc > 0 && new_histogram_idx < new_histogram.size()) {
186 const int64_t old_histogram_val = new_histogram[new_histogram_idx];
187 new_histogram[new_histogram_idx] =
188 rtc::saturated_cast<int>(old_histogram_val + acc);
189 acc -= new_histogram[new_histogram_idx] - old_histogram_val;
190 new_histogram_idx++;
191 }
192 RTC_DCHECK_EQ(buckets.size(), new_histogram.size());
193 if (acc == 0) {
194 // If acc is non-zero, we were not able to add everything to the new
195 // histogram, so this check will not hold.
196 RTC_DCHECK_EQ(accumulate(buckets.begin(), buckets.end(), 0ll),
197 accumulate(new_histogram.begin(), new_histogram.end(), 0ll));
198 }
199 return new_histogram;
200}
201
202} // namespace webrtc