Debian Codegraph @

srtcore/buffer_tools.h

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 /*****************************************************************************
12 Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois.
13 All rights reserved.
14
15 Redistribution and use in source and binary forms, with or without
16 modification, are permitted provided that the following conditions are
17 met:
18
19 * Redistributions of source code must retain the above
20 copyright notice, this list of conditions and the
21 following disclaimer.
22
23 * Redistributions in binary form must reproduce the
24 above copyright notice, this list of conditions
25 and the following disclaimer in the documentation
26 and/or other materials provided with the distribution.
27
28 * Neither the name of the University of Illinois
29 nor the names of its contributors may be used to
30 endorse or promote products derived from this
31 software without specific prior written permission.
32
33 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
34 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
35 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
36 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 *****************************************************************************/
45
46 /*****************************************************************************
47 written by
48 Yunhong Gu, last updated 05/05/2009
49 modified by
50 Haivision Systems Inc.
51 *****************************************************************************/
52
53 #ifndef INC_SRT_BUFFER_TOOLS_H
54 #define INC_SRT_BUFFER_TOOLS_H
55
56 #include "common.h"
57
58 namespace srt
59 {
60
61 /// The AvgBufSize class is used to calculate moving average of the buffer (RCV or SND)
62 class AvgBufSize
63 {
64 typedef sync::steady_clock::time_point time_point;
65
66 public:
67 AvgBufSize()
68 : m_dBytesCountMAvg(0.0)
69 , m_dCountMAvg(0.0)
70 , m_dTimespanMAvg(0.0)
71 {
72 }
73
74 public:
75 bool isTimeToUpdate(const time_point& now) const;
76 void update(const time_point& now, int pkts, int bytes, int timespan_ms);
77
78 public:
79 inline double pkts() const { return m_dCountMAvg; }
80 inline double timespan_ms() const { return m_dTimespanMAvg; }
81 inline double bytes() const { return m_dBytesCountMAvg; }
82
83 private:
84 time_point m_tsLastSamplingTime;
85 double m_dBytesCountMAvg;
86 double m_dCountMAvg;
87 double m_dTimespanMAvg;
88 };
89
90 /// The class to estimate source bitrate based on samples submitted to the buffer.
91 /// Is currently only used by the CSndBuffer.
92 class CRateEstimator
93 {
94 typedef sync::steady_clock::time_point time_point;
95 typedef sync::steady_clock::duration duration;
96 public:
97 CRateEstimator(int family);
98
99 public:
100 uint64_t getInRatePeriod() const { return m_InRatePeriod; }
101
102 /// Retrieve input bitrate in bytes per second
103 int getInputRate() const { return m_iInRateBps; }
104
105 void setInputRateSmpPeriod(int period);
106
107 /// Update input rate calculation.
108 /// @param [in] time current time
109 /// @param [in] pkts number of packets newly added to the buffer
110 /// @param [in] bytes number of payload bytes in those newly added packets
111 void updateInputRate(const time_point& time, int pkts = 0, int bytes = 0);
112
113 void resetInputRateSmpPeriod(bool disable = false) { setInputRateSmpPeriod(disable ? 0 : INPUTRATE_FAST_START_US); }
114
115 private: // Constants
116 static const uint64_t INPUTRATE_FAST_START_US = 500000; // 500 ms
117 static const uint64_t INPUTRATE_RUNNING_US = 1000000; // 1000 ms
118 static const int64_t INPUTRATE_MAX_PACKETS = 2000; // ~ 21 Mbps of 1316 bytes payload
119 static const int INPUTRATE_INITIAL_BYTESPS = BW_INFINITE;
120
121 private:
122 int m_iInRatePktsCount; // number of payload packets added since InRateStartTime.
123 int m_iInRateBytesCount; // number of payload bytes added since InRateStartTime.
124 time_point m_tsInRateStartTime;
125 uint64_t m_InRatePeriod; // usec
126 int m_iInRateBps; // Input Rate in Bytes/sec
127 int m_iFullHeaderSize;
128 };
129
130
131 class CSndRateEstimator
132 {
133 typedef sync::steady_clock::time_point time_point;
134
135 public:
136 CSndRateEstimator(const time_point& tsNow);
137
138 /// Add sample.
139 /// @param [in] time sample (sending) time.
140 /// @param [in] pkts number of packets in the sample.
141 /// @param [in] bytes number of payload bytes in the sample.
142 void addSample(const time_point& time, int pkts = 0, size_t bytes = 0);
143
144 /// Retrieve estimated bitrate in bytes per second with 16-byte packet header.
145 int getRate() const { return m_iRateBps; }
146
147 /// Retrieve estimated bitrate in bytes per second (with 16-byte packet header)
148 /// including the current sampling interval.
149 int getCurrentRate() const;
150
151 private:
152 static const int NUM_PERIODS = 10;
153 static const int SAMPLE_DURATION_MS = 100; // 100 ms
154 struct Sample
155 {
156 int m_iPktsCount; // number of payload packets
157 int m_iBytesCount; // number of payload bytes
158
159 void reset()
160 {
161 m_iPktsCount = 0;
162 m_iBytesCount = 0;
163 }
164
165 Sample()
166 : m_iPktsCount(0)
167 , m_iBytesCount(0)
168 {
169 }
170
171 Sample(int iPkts, int iBytes)
172 : m_iPktsCount(iPkts)
173 , m_iBytesCount(iBytes)
174 {
175 }
176
177 Sample operator+(const Sample& other)
178 {
179 return Sample(m_iPktsCount + other.m_iPktsCount, m_iBytesCount + other.m_iBytesCount);
180 }
181
182 Sample& operator+=(const Sample& other)
183 {
184 *this = *this + other;
185 return *this;
186 }
187
188 bool empty() const { return m_iPktsCount == 0; }
189 };
190
191 int incSampleIdx(int val, int inc = 1) const;
192
193 Sample m_Samples[NUM_PERIODS];
194
195 time_point m_tsFirstSampleTime; //< Start time of the first sample.
196 int m_iFirstSampleIdx; //< Index of the first sample.
197 int m_iCurSampleIdx; //< Index of the current sample being collected.
198 int m_iRateBps; //< Rate in Bytes/sec.
199 };
200
201 // Utility class for bandwidth limitation
202 class CShaper
203 {
204 public:
205 static double SHAPER_RESOLUTION_US() { return 1000000.; } // micro seconds
206 static double BURSTPERIOD_DEFAULT() { return 100; }
207
208 typedef sync::steady_clock::time_point time_point;
209 typedef sync::steady_clock::duration duration;
210 CShaper (double min_tokens_capacity):
211 m_BurstPeriod(sync::milliseconds_from(BURSTPERIOD_DEFAULT())),
212 m_rate_Bps(0),
213 m_tokens(0),
214 m_tokensCapacity(0),
215 m_minTokensCapacity(min_tokens_capacity)
216 {
217
218 }
219
220 // Token capacity should be settable later
221 void setMinimumTokenCapacity(double cap)
222 {
223 m_minTokensCapacity = cap;
224 updateLimits();
225 }
226
227 private:
228 duration m_BurstPeriod;
229 double m_rate_Bps; // current_bitrate in Bytes per second
230 double m_tokens; // in bytes
231 double m_tokensCapacity; // in bytes
232 double m_minTokensCapacity;
233 time_point m_UpdateTime;
234 void setTokenCapacity(double tokens)
235 {
236 m_tokensCapacity = std::max(0., tokens);
237 }
238
239 void setTokens(double tokens)
240 {
241 // It is allowed to set the negative number of tokens,
242 // just not less than the negative maximum
243 m_tokens = Bounds(1 - m_tokensCapacity, tokens, m_tokensCapacity);
244 }
245
246 static double periodToTokens(double rate_Bps, duration period)
247 {
248 double seconds = double(sync::count_microseconds(period)) / SHAPER_RESOLUTION_US();
249 return rate_Bps * seconds;
250 }
251
252 static duration tokensToPeriod(double rate_Bps, double tokens)
253 {
254 double seconds = tokens / rate_Bps;
255 return sync::microseconds_from(seconds * SHAPER_RESOLUTION_US());
256 }
257
258 void updateLimits()
259 {
260 double token_cap = periodToTokens(m_rate_Bps, m_BurstPeriod);
261 if (token_cap < m_minTokensCapacity)
262 {
263 // We have a too small value; recalculate the burst period to reach the minimum.
264 duration minperiod = tokensToPeriod(m_rate_Bps, m_minTokensCapacity);
265 token_cap = m_minTokensCapacity;
266 m_BurstPeriod = minperiod;
267 }
268 setTokenCapacity(token_cap);
269 }
270
271 public:
272 void setBitrate(double bw_Bps)
273 {
274 // NOTE: comparison on double to check the PREVIOUSLY
275 // SET value (m_rate_Bps), not recalculated value.
276 if (bw_Bps != m_rate_Bps)
277 {
278 m_rate_Bps = bw_Bps;
279 updateLimits();
280 }
281 }
282
283 void setMinimumBurstPeriod(duration hp)
284 {
285 if (m_BurstPeriod < hp)
286 {
287 setBurstPeriod(hp);
288 }
289 }
290
291 void setBurstPeriod(duration bp)
292 {
293 if (bp != m_BurstPeriod)
294 {
295 m_BurstPeriod = bp;
296 updateLimits();
297 }
298 }
299
300 // Note that tick() must be always called after setBitrate.
301 void tick(const time_point& now)
302 {
303 duration delta = now - m_UpdateTime;
304 m_UpdateTime = now;
305
306 double update_tokens = periodToTokens(m_rate_Bps, delta);
307 setTokens(update_tokens + m_tokens);
308 }
309
310 bool enoughTokens(double len) const { return len <= m_tokens; }
311 void consumeTokens(double len) { setTokens(m_tokens - len); }
312
313
314 // For debug purposes
315 int ntokens() const { return m_tokens; }
316 duration burstPeriod() const { return m_BurstPeriod; }
317 int maxTokens() const { return m_tokensCapacity; }
318 // TOKENS = BITRATE * BURST_PERIOD / (SHAPER_UNIT * SHAPER_RESOLUTION_US)
319 // TOKENS * SHAPER_UNIT * SHAPER_RESOLUTION_US = BITRATE * BURST_PERIOD
320 // BITRATE = (TOKENS * SHAPER_UNIT * SHAPER_RESOLUTION_US) / (BURST_PERIOD)
321 double tokenRate_Bps(double tokens) const
322 {
323 return (tokens * SHAPER_RESOLUTION_US()) / (sync::count_microseconds(m_BurstPeriod));
324 }
325 double availRate_Bps() const { return tokenRate_Bps(m_tokens); }
326 double usedRate_Bps() const { return tokenRate_Bps(m_tokensCapacity - m_tokens); }
327 };
328 } // namespace srt
329
330 #endif