File indexing completed on 2025-01-05 04:37:33

0001 /*
0002     SPDX-FileCopyrightText: 2010 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "delaywindow.h"
0008 #include <algorithm>
0009 #include <util/functions.h>
0010 #include <util/log.h>
0011 
0012 using namespace bt;
0013 
0014 namespace utp
0015 {
0016 DelayWindow::DelayWindow()
0017     : delay_window(100)
0018 {
0019 }
0020 
0021 DelayWindow::~DelayWindow()
0022 {
0023 }
0024 
0025 bt::Uint32 DelayWindow::update(const utp::Header *hdr, bt::TimeStamp receive_time)
0026 {
0027     // First cleanup old values at the beginning
0028     DelayEntryItr itr = delay_window.begin();
0029     while (itr != delay_window.end()) {
0030         // drop everything older then 2 minutes
0031         if (receive_time - itr->receive_time > DELAY_WINDOW_SIZE) {
0032             // Old entry, can remove it
0033             itr = delay_window.erase(itr);
0034         } else
0035             break;
0036     }
0037 
0038     // If we are on the end or the new value has a lower delay, clear the list and insert at front
0039     if (itr == delay_window.end() || hdr->timestamp_difference_microseconds < itr->timestamp_difference_microseconds) {
0040         delay_window.clear();
0041         if (delay_window.full())
0042             delay_window.set_capacity(delay_window.capacity() + 100);
0043 
0044         delay_window.push_back(DelayEntry(hdr->timestamp_difference_microseconds, receive_time));
0045         return hdr->timestamp_difference_microseconds;
0046     }
0047 
0048     // Use binary search to find the position where we need to insert
0049     DelayEntry entry(hdr->timestamp_difference_microseconds, receive_time);
0050     itr = std::lower_bound(delay_window.begin(), delay_window.end(), entry);
0051     // Everything until the end has a higher delay then the new sample and is older.
0052     // So they can all be dropped, because they can never be the minimum delay again.
0053     if (itr != delay_window.end())
0054         delay_window.erase(itr, delay_window.end());
0055 
0056     delay_window.push_back(entry);
0057 
0058     // Out(SYS_GEN|LOG_DEBUG) << "Delay window: " << delay_window.size() << endl;
0059     return delay_window.front().timestamp_difference_microseconds;
0060 }
0061 
0062 }