blob: 619d542c4aa5159b01ac4cb83424f1ce37fc997a [file] [log] [blame]
Erik Språngc5922572024-07-04 15:28:521/*
2 * Copyright (c) 2024 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#ifndef VIDEO_RATE_UTILIZATION_TRACKER_H_
12#define VIDEO_RATE_UTILIZATION_TRACKER_H_
13
14#include <deque>
Florent Castelli8037fc62024-08-29 13:00:4015#include <optional>
Erik Språngc5922572024-07-04 15:28:5216
Erik Språngc5922572024-07-04 15:28:5217#include "api/units/data_rate.h"
18#include "api/units/data_size.h"
19#include "api/units/time_delta.h"
20#include "api/units/timestamp.h"
21
22namespace webrtc {
23
24// Helper class that tracks the rate of utilization over a sliding window.
25// tl;dr: if an encoder has a target rate of 1000kbps but in practice
26// produces 500kbps it would have a utilization factor of 0.5.
27// The tracker looks only at discrete events, and keeps only a fixed amount
28// of data points (e.g. encoded frames) or points newer than a given time
29// limit, whichever is lower.
30
31// More precisely This class measures the allocated cumulative byte budget (as
32// specified by one or more rate updates) and the actual cumulative number of
33// bytes produced over a sliding window. A utilization factor (produced bytes /
34// budgeted bytes) is calculated seen from the first data point timestamp until
35// the last data point timestamp plus the amount time needed to send that last
36// data point given no further updates to the rate. The implication of this is a
37// smoother value, and e.g. setting a rate and adding a data point, then
38// immediately querying the utilization reports 1.0 utilization instead of some
39// undefined state.
40
41class RateUtilizationTracker {
42 public:
43 RateUtilizationTracker(size_t max_num_encoded_data_points,
44 TimeDelta max_duration);
45
46 // The timestamps used should never decrease relative the last one.
47 void OnDataRateChanged(DataRate rate, Timestamp time);
48 void OnDataProduced(DataSize size, Timestamp time);
Florent Castelli8037fc62024-08-29 13:00:4049 std::optional<double> GetRateUtilizationFactor(Timestamp time) const;
Erik Språngc5922572024-07-04 15:28:5250
51 private:
52 struct RateUsageUpdate {
53 Timestamp time;
54 DataRate target_rate;
55 DataSize produced_data;
56 };
57
58 void CullOldData(Timestamp time);
59
60 const size_t max_data_points_;
61 const TimeDelta max_duration_;
62 DataRate current_rate_;
63 std::deque<RateUsageUpdate> data_points_;
64};
65
66} // namespace webrtc
67
68#endif // VIDEO_RATE_UTILIZATION_TRACKER_H_