buffer_tools.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without
  14. modification, are permitted provided that the following conditions are
  15. met:
  16. * Redistributions of source code must retain the above
  17. copyright notice, this list of conditions and the
  18. following disclaimer.
  19. * Redistributions in binary form must reproduce the
  20. above copyright notice, this list of conditions
  21. and the following disclaimer in the documentation
  22. and/or other materials provided with the distribution.
  23. * Neither the name of the University of Illinois
  24. nor the names of its contributors may be used to
  25. endorse or promote products derived from this
  26. software without specific prior written permission.
  27. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  28. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  29. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  30. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  32. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  34. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  35. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  36. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  37. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *****************************************************************************/
  39. /*****************************************************************************
  40. written by
  41. Yunhong Gu, last updated 03/12/2011
  42. modified by
  43. Haivision Systems Inc.
  44. *****************************************************************************/
  45. #include "platform_sys.h"
  46. #include "buffer_tools.h"
  47. #include "packet.h"
  48. #include "logger_defs.h"
  49. #include "utilities.h"
  50. namespace srt {
  51. using namespace std;
  52. using namespace srt_logging;
  53. using namespace sync;
  54. // You can change this value at build config by using "ENFORCE" options.
  55. #if !defined(SRT_MAVG_SAMPLING_RATE)
  56. #define SRT_MAVG_SAMPLING_RATE 40
  57. #endif
  58. bool AvgBufSize::isTimeToUpdate(const time_point& now) const
  59. {
  60. const int usMAvgBasePeriod = 1000000; // 1s in microseconds
  61. const int us2ms = 1000;
  62. const int msMAvgPeriod = (usMAvgBasePeriod / SRT_MAVG_SAMPLING_RATE) / us2ms;
  63. const uint64_t elapsed_ms = count_milliseconds(now - m_tsLastSamplingTime); // ms since last sampling
  64. return (elapsed_ms >= msMAvgPeriod);
  65. }
  66. void AvgBufSize::update(const steady_clock::time_point& now, int pkts, int bytes, int timespan_ms)
  67. {
  68. const uint64_t elapsed_ms = count_milliseconds(now - m_tsLastSamplingTime); // ms since last sampling
  69. m_tsLastSamplingTime = now;
  70. const uint64_t one_second_in_ms = 1000;
  71. if (elapsed_ms > one_second_in_ms)
  72. {
  73. // No sampling in last 1 sec, initialize average
  74. m_dCountMAvg = pkts;
  75. m_dBytesCountMAvg = bytes;
  76. m_dTimespanMAvg = timespan_ms;
  77. return;
  78. }
  79. //
  80. // weight last average value between -1 sec and last sampling time (LST)
  81. // and new value between last sampling time and now
  82. // |elapsed_ms|
  83. // +----------------------------------+-------+
  84. // -1 LST 0(now)
  85. //
  86. m_dCountMAvg = avg_iir_w<1000, double>(m_dCountMAvg, pkts, elapsed_ms);
  87. m_dBytesCountMAvg = avg_iir_w<1000, double>(m_dBytesCountMAvg, bytes, elapsed_ms);
  88. m_dTimespanMAvg = avg_iir_w<1000, double>(m_dTimespanMAvg, timespan_ms, elapsed_ms);
  89. }
  90. CRateEstimator::CRateEstimator()
  91. : m_iInRatePktsCount(0)
  92. , m_iInRateBytesCount(0)
  93. , m_InRatePeriod(INPUTRATE_FAST_START_US) // 0.5 sec (fast start)
  94. , m_iInRateBps(INPUTRATE_INITIAL_BYTESPS)
  95. {}
  96. void CRateEstimator::setInputRateSmpPeriod(int period)
  97. {
  98. m_InRatePeriod = (uint64_t)period; //(usec) 0=no input rate calculation
  99. }
  100. void CRateEstimator::updateInputRate(const time_point& time, int pkts, int bytes)
  101. {
  102. // no input rate calculation
  103. if (m_InRatePeriod == 0)
  104. return;
  105. if (is_zero(m_tsInRateStartTime))
  106. {
  107. m_tsInRateStartTime = time;
  108. return;
  109. }
  110. else if (time < m_tsInRateStartTime)
  111. {
  112. // Old packets are being submitted for estimation, e.g. during the backup link activation.
  113. return;
  114. }
  115. m_iInRatePktsCount += pkts;
  116. m_iInRateBytesCount += bytes;
  117. // Trigger early update in fast start mode
  118. const bool early_update = (m_InRatePeriod < INPUTRATE_RUNNING_US) && (m_iInRatePktsCount > INPUTRATE_MAX_PACKETS);
  119. const uint64_t period_us = count_microseconds(time - m_tsInRateStartTime);
  120. if (!early_update && period_us <= m_InRatePeriod)
  121. return;
  122. // Required Byte/sec rate (payload + headers)
  123. m_iInRateBytesCount += (m_iInRatePktsCount * CPacket::SRT_DATA_HDR_SIZE);
  124. m_iInRateBps = (int)(((int64_t)m_iInRateBytesCount * 1000000) / period_us);
  125. HLOGC(bslog.Debug,
  126. log << "updateInputRate: pkts:" << m_iInRateBytesCount << " bytes:" << m_iInRatePktsCount
  127. << " rate=" << (m_iInRateBps * 8) / 1000 << "kbps interval=" << period_us);
  128. m_iInRatePktsCount = 0;
  129. m_iInRateBytesCount = 0;
  130. m_tsInRateStartTime = time;
  131. setInputRateSmpPeriod(INPUTRATE_RUNNING_US);
  132. }
  133. CSndRateEstimator::CSndRateEstimator(const time_point& tsNow)
  134. : m_tsFirstSampleTime(tsNow)
  135. , m_iFirstSampleIdx(0)
  136. , m_iCurSampleIdx(0)
  137. , m_iRateBps(0)
  138. {
  139. }
  140. void CSndRateEstimator::addSample(const time_point& ts, int pkts, size_t bytes)
  141. {
  142. const int iSampleDeltaIdx = (int) count_milliseconds(ts - m_tsFirstSampleTime) / SAMPLE_DURATION_MS;
  143. const int delta = NUM_PERIODS - iSampleDeltaIdx;
  144. // TODO: -delta <= NUM_PERIODS, then just reset the state on the estimator.
  145. if (iSampleDeltaIdx >= 2 * NUM_PERIODS)
  146. {
  147. // Just reset the estimator and start like if new.
  148. for (int i = 0; i < NUM_PERIODS; ++i)
  149. {
  150. const int idx = incSampleIdx(m_iFirstSampleIdx, i);
  151. m_Samples[idx].reset();
  152. if (idx == m_iCurSampleIdx)
  153. break;
  154. }
  155. m_iFirstSampleIdx = 0;
  156. m_iCurSampleIdx = 0;
  157. m_iRateBps = 0;
  158. m_tsFirstSampleTime += milliseconds_from(iSampleDeltaIdx * SAMPLE_DURATION_MS);
  159. }
  160. else if (iSampleDeltaIdx > NUM_PERIODS)
  161. {
  162. // In run-time a constant flow of samples is expected. Once all periods are filled (after 1 second of sampling),
  163. // the iSampleDeltaIdx should be either (NUM_PERIODS - 1),
  164. // or NUM_PERIODS. In the later case it means the start of a new sampling period.
  165. int d = delta;
  166. while (d < 0)
  167. {
  168. m_Samples[m_iFirstSampleIdx].reset();
  169. m_iFirstSampleIdx = incSampleIdx(m_iFirstSampleIdx);
  170. m_tsFirstSampleTime += milliseconds_from(SAMPLE_DURATION_MS);
  171. m_iCurSampleIdx = incSampleIdx(m_iCurSampleIdx);
  172. ++d;
  173. }
  174. }
  175. // Check if the new sample period has started.
  176. const int iNewDeltaIdx = (int) count_milliseconds(ts - m_tsFirstSampleTime) / SAMPLE_DURATION_MS;
  177. if (incSampleIdx(m_iFirstSampleIdx, iNewDeltaIdx) != m_iCurSampleIdx)
  178. {
  179. // Now there should be some periods (at most last NUM_PERIODS) ready to be summed,
  180. // rate estimation updated, after which all the new entry should be added.
  181. Sample sum;
  182. int iNumPeriods = 0;
  183. bool bMetNonEmpty = false;
  184. for (int i = 0; i < NUM_PERIODS; ++i)
  185. {
  186. const int idx = incSampleIdx(m_iFirstSampleIdx, i);
  187. const Sample& s = m_Samples[idx];
  188. sum += s;
  189. if (bMetNonEmpty || !s.empty())
  190. {
  191. ++iNumPeriods;
  192. bMetNonEmpty = true;
  193. }
  194. if (idx == m_iCurSampleIdx)
  195. break;
  196. }
  197. if (iNumPeriods == 0)
  198. {
  199. m_iRateBps = 0;
  200. }
  201. else
  202. {
  203. m_iRateBps = sum.m_iBytesCount * 1000 / (iNumPeriods * SAMPLE_DURATION_MS);
  204. }
  205. HLOGC(bslog.Note,
  206. log << "CSndRateEstimator: new rate estimation :" << (m_iRateBps * 8) / 1000 << " kbps. Based on "
  207. << iNumPeriods << " periods, " << sum.m_iPktsCount << " packets, " << sum.m_iBytesCount << " bytes.");
  208. // Shift one sampling period to start collecting the new one.
  209. m_iCurSampleIdx = incSampleIdx(m_iCurSampleIdx);
  210. m_Samples[m_iCurSampleIdx].reset();
  211. // If all NUM_SAMPLES are recorded, the first position has to be shifted as well.
  212. if (delta <= 0)
  213. {
  214. m_iFirstSampleIdx = incSampleIdx(m_iFirstSampleIdx);
  215. m_tsFirstSampleTime += milliseconds_from(SAMPLE_DURATION_MS);
  216. }
  217. }
  218. m_Samples[m_iCurSampleIdx].m_iBytesCount += bytes;
  219. m_Samples[m_iCurSampleIdx].m_iPktsCount += pkts;
  220. }
  221. int CSndRateEstimator::getCurrentRate() const
  222. {
  223. SRT_ASSERT(m_iCurSampleIdx >= 0 && m_iCurSampleIdx < NUM_PERIODS);
  224. return (int) avg_iir<16, unsigned long long>(m_iRateBps, m_Samples[m_iCurSampleIdx].m_iBytesCount * 1000 / SAMPLE_DURATION_MS);
  225. }
  226. int CSndRateEstimator::incSampleIdx(int val, int inc) const
  227. {
  228. SRT_ASSERT(inc >= 0 && inc <= NUM_PERIODS);
  229. val += inc;
  230. while (val >= NUM_PERIODS)
  231. val -= NUM_PERIODS;
  232. return val;
  233. }
  234. }