| 165 | } |
| 166 | |
| 167 | void CSndRateEstimator::addSample(const time_point& ts, int pkts, size_t bytes) |
| 168 | { |
| 169 | const int iSampleDeltaIdx = (int) count_milliseconds(ts - m_tsFirstSampleTime) / SAMPLE_DURATION_MS; |
| 170 | const int delta = NUM_PERIODS - iSampleDeltaIdx; |
| 171 | |
| 172 | // TODO: -delta <= NUM_PERIODS, then just reset the state on the estimator. |
| 173 | |
| 174 | if (iSampleDeltaIdx >= 2 * NUM_PERIODS) |
| 175 | { |
| 176 | // Just reset the estimator and start like if new. |
| 177 | for (int i = 0; i < NUM_PERIODS; ++i) |
| 178 | { |
| 179 | const int idx = incSampleIdx(m_iFirstSampleIdx, i); |
| 180 | m_Samples[idx].reset(); |
| 181 | |
| 182 | if (idx == m_iCurSampleIdx) |
| 183 | break; |
| 184 | } |
| 185 | |
| 186 | m_iFirstSampleIdx = 0; |
| 187 | m_iCurSampleIdx = 0; |
| 188 | m_iRateBps = 0; |
| 189 | m_tsFirstSampleTime += milliseconds_from(iSampleDeltaIdx * SAMPLE_DURATION_MS); |
| 190 | } |
| 191 | else if (iSampleDeltaIdx > NUM_PERIODS) |
| 192 | { |
| 193 | // In run-time a constant flow of samples is expected. Once all periods are filled (after 1 second of sampling), |
| 194 | // the iSampleDeltaIdx should be either (NUM_PERIODS - 1), |
| 195 | // or NUM_PERIODS. In the later case it means the start of a new sampling period. |
| 196 | int d = delta; |
| 197 | while (d < 0) |
| 198 | { |
| 199 | m_Samples[m_iFirstSampleIdx].reset(); |
| 200 | m_iFirstSampleIdx = incSampleIdx(m_iFirstSampleIdx); |
| 201 | m_tsFirstSampleTime += milliseconds_from(SAMPLE_DURATION_MS); |
| 202 | m_iCurSampleIdx = incSampleIdx(m_iCurSampleIdx); |
| 203 | ++d; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // Check if the new sample period has started. |
| 208 | const int iNewDeltaIdx = (int) count_milliseconds(ts - m_tsFirstSampleTime) / SAMPLE_DURATION_MS; |
| 209 | if (incSampleIdx(m_iFirstSampleIdx, iNewDeltaIdx) != m_iCurSampleIdx) |
| 210 | { |
| 211 | // Now there should be some periods (at most last NUM_PERIODS) ready to be summed, |
| 212 | // rate estimation updated, after which all the new entry should be added. |
| 213 | Sample sum; |
| 214 | int iNumPeriods = 0; |
| 215 | bool bMetNonEmpty = false; |
| 216 | for (int i = 0; i < NUM_PERIODS; ++i) |
| 217 | { |
| 218 | const int idx = incSampleIdx(m_iFirstSampleIdx, i); |
| 219 | const Sample& s = m_Samples[idx]; |
| 220 | sum += s; |
| 221 | if (bMetNonEmpty || !s.empty()) |
| 222 | { |
| 223 | ++iNumPeriods; |
| 224 | bMetNonEmpty = true; |