xref: /aosp_15_r20/external/webrtc/rtc_base/rate_tracker.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2015 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 "rtc_base/rate_tracker.h"
12 
13 #include <algorithm>
14 
15 #include "rtc_base/checks.h"
16 #include "rtc_base/time_utils.h"
17 
18 namespace rtc {
19 
20 static const int64_t kTimeUnset = -1;
21 
RateTracker(int64_t bucket_milliseconds,size_t bucket_count)22 RateTracker::RateTracker(int64_t bucket_milliseconds, size_t bucket_count)
23     : bucket_milliseconds_(bucket_milliseconds),
24       bucket_count_(bucket_count),
25       sample_buckets_(new int64_t[bucket_count + 1]),
26       total_sample_count_(0u),
27       bucket_start_time_milliseconds_(kTimeUnset) {
28   RTC_CHECK(bucket_milliseconds > 0);
29   RTC_CHECK(bucket_count > 0);
30 }
31 
~RateTracker()32 RateTracker::~RateTracker() {
33   delete[] sample_buckets_;
34 }
35 
ComputeRateForInterval(int64_t interval_milliseconds) const36 double RateTracker::ComputeRateForInterval(
37     int64_t interval_milliseconds) const {
38   if (bucket_start_time_milliseconds_ == kTimeUnset) {
39     return 0.0;
40   }
41   int64_t current_time = Time();
42   // Calculate which buckets to sum up given the current time.  If the time
43   // has passed to a new bucket then we have to skip some of the oldest buckets.
44   int64_t available_interval_milliseconds =
45       std::min(interval_milliseconds,
46                bucket_milliseconds_ * static_cast<int64_t>(bucket_count_));
47   // number of old buckets (i.e. after the current bucket in the ring buffer)
48   // that are expired given our current time interval.
49   size_t buckets_to_skip;
50   // Number of milliseconds of the first bucket that are not a portion of the
51   // current interval.
52   int64_t milliseconds_to_skip;
53   if (current_time >
54       initialization_time_milliseconds_ + available_interval_milliseconds) {
55     int64_t time_to_skip =
56         current_time - bucket_start_time_milliseconds_ +
57         static_cast<int64_t>(bucket_count_) * bucket_milliseconds_ -
58         available_interval_milliseconds;
59     buckets_to_skip = time_to_skip / bucket_milliseconds_;
60     milliseconds_to_skip = time_to_skip % bucket_milliseconds_;
61   } else {
62     buckets_to_skip = bucket_count_ - current_bucket_;
63     milliseconds_to_skip = 0;
64     available_interval_milliseconds =
65         TimeDiff(current_time, initialization_time_milliseconds_);
66     // Let one bucket interval pass after initialization before reporting.
67     if (available_interval_milliseconds < bucket_milliseconds_) {
68       return 0.0;
69     }
70   }
71   // If we're skipping all buckets that means that there have been no samples
72   // within the sampling interval so report 0.
73   if (buckets_to_skip > bucket_count_ || available_interval_milliseconds == 0) {
74     return 0.0;
75   }
76   size_t start_bucket = NextBucketIndex(current_bucket_ + buckets_to_skip);
77   // Only count a portion of the first bucket according to how much of the
78   // first bucket is within the current interval.
79   int64_t total_samples = ((sample_buckets_[start_bucket] *
80                             (bucket_milliseconds_ - milliseconds_to_skip)) +
81                            (bucket_milliseconds_ >> 1)) /
82                           bucket_milliseconds_;
83   // All other buckets in the interval are counted in their entirety.
84   for (size_t i = NextBucketIndex(start_bucket);
85        i != NextBucketIndex(current_bucket_); i = NextBucketIndex(i)) {
86     total_samples += sample_buckets_[i];
87   }
88   // Convert to samples per second.
89   return static_cast<double>(total_samples * 1000) /
90          static_cast<double>(available_interval_milliseconds);
91 }
92 
ComputeTotalRate() const93 double RateTracker::ComputeTotalRate() const {
94   if (bucket_start_time_milliseconds_ == kTimeUnset) {
95     return 0.0;
96   }
97   int64_t current_time = Time();
98   if (current_time <= initialization_time_milliseconds_) {
99     return 0.0;
100   }
101   return static_cast<double>(total_sample_count_ * 1000) /
102          static_cast<double>(
103              TimeDiff(current_time, initialization_time_milliseconds_));
104 }
105 
TotalSampleCount() const106 int64_t RateTracker::TotalSampleCount() const {
107   return total_sample_count_;
108 }
109 
AddSamples(int64_t sample_count)110 void RateTracker::AddSamples(int64_t sample_count) {
111   AddSamplesAtTime(Time(), sample_count);
112 }
113 
AddSamplesAtTime(int64_t current_time_ms,int64_t sample_count)114 void RateTracker::AddSamplesAtTime(int64_t current_time_ms,
115                                    int64_t sample_count) {
116   RTC_DCHECK_LE(0, sample_count);
117   EnsureInitialized();
118   // Advance the current bucket as needed for the current time, and reset
119   // bucket counts as we advance.
120   for (size_t i = 0; i <= bucket_count_ &&
121                      current_time_ms >=
122                          bucket_start_time_milliseconds_ + bucket_milliseconds_;
123        ++i) {
124     bucket_start_time_milliseconds_ += bucket_milliseconds_;
125     current_bucket_ = NextBucketIndex(current_bucket_);
126     sample_buckets_[current_bucket_] = 0;
127   }
128   // Ensure that bucket_start_time_milliseconds_ is updated appropriately if
129   // the entire buffer of samples has been expired.
130   bucket_start_time_milliseconds_ +=
131       bucket_milliseconds_ *
132       ((current_time_ms - bucket_start_time_milliseconds_) /
133        bucket_milliseconds_);
134   // Add all samples in the bucket that includes the current time.
135   sample_buckets_[current_bucket_] += sample_count;
136   total_sample_count_ += sample_count;
137 }
138 
Time() const139 int64_t RateTracker::Time() const {
140   return rtc::TimeMillis();
141 }
142 
EnsureInitialized()143 void RateTracker::EnsureInitialized() {
144   if (bucket_start_time_milliseconds_ == kTimeUnset) {
145     initialization_time_milliseconds_ = Time();
146     bucket_start_time_milliseconds_ = initialization_time_milliseconds_;
147     current_bucket_ = 0;
148     // We only need to initialize the first bucket because we reset buckets when
149     // current_bucket_ increments.
150     sample_buckets_[current_bucket_] = 0;
151   }
152 }
153 
NextBucketIndex(size_t bucket_index) const154 size_t RateTracker::NextBucketIndex(size_t bucket_index) const {
155   return (bucket_index + 1u) % (bucket_count_ + 1u);
156 }
157 
158 }  // namespace rtc
159