]> git.localhorst.tv Git - blank.git/blob - src/net/CongestionControl.hpp
move steering behaviours into entity
[blank.git] / src / net / CongestionControl.hpp
1 #ifndef BLANK_NET_CONGESTIONCONTROL_HPP_
2 #define BLANK_NET_CONGESTIONCONTROL_HPP_
3
4 #include <cstdint>
5 #include <SDL_net.h>
6
7
8 namespace blank {
9
10 class CongestionControl {
11
12 public:
13         enum Mode {
14                 GOOD,
15                 BAD,
16                 UGLY,
17         };
18
19 public:
20         CongestionControl();
21
22         /// get recommended mode of operation
23         Mode GetMode() const noexcept { return mode; }
24         /// according to current mode, drop this many unimportant packets
25         unsigned int SuggestedPacketSkip() const noexcept { return (1 << mode) - 1; }
26         /// according to current mode, pause between large uncritical packets for this many ticks
27         unsigned int SuggestedPacketHold() const noexcept { return (1 << (mode + 1)) - 1; }
28
29         /// packet loss as factor
30         float PacketLoss() const noexcept { return packet_loss; }
31         /// smooth average round trip time in milliseconds
32         float RoundTripTime() const noexcept { return rtt; }
33         /// estimated kilobytes transferred per second
34         float Upstream() const noexcept { return tx_kbps; }
35         /// estimated kilobytes received per second
36         float Downstream() const noexcept { return rx_kbps; }
37
38         void PacketSent(std::uint16_t) noexcept;
39         void PacketLost(std::uint16_t) noexcept;
40         void PacketReceived(std::uint16_t) noexcept;
41
42         void PacketIn(const UDPpacket &) noexcept;
43         void PacketOut(const UDPpacket &) noexcept;
44
45 private:
46         void UpdatePacketLoss() noexcept;
47
48         void UpdateRTT(std::uint16_t) noexcept;
49         bool SamplePacket(std::uint16_t) const noexcept;
50         std::size_t SampleIndex(std::uint16_t) const noexcept;
51
52         void UpdateStats() noexcept;
53
54         void UpdateMode() noexcept;
55         void CheckUpgrade(Mode) noexcept;
56         void ChangeMode(Mode) noexcept;
57         void KeepMode() noexcept;
58
59         Mode Conditions() const noexcept;
60
61 private:
62         const unsigned int packet_overhead;
63         const unsigned int sample_skip;
64
65         unsigned int packets_lost;
66         unsigned int packets_received;
67         float packet_loss;
68
69         Uint32 stamps[16];
70         std::uint16_t stamp_last;
71         float rtt;
72
73         Uint32 next_sample;
74         std::size_t tx_bytes;
75         std::size_t rx_bytes;
76         float tx_kbps;
77         float rx_kbps;
78
79         Mode mode;
80         float bad_rtt;
81         float bad_loss;
82         float ugly_rtt;
83         float ugly_loss;
84         Uint32 mode_entered;
85         Uint32 mode_reset;
86         Uint32 mode_keep_time;
87         Uint32 mode_step;
88
89 };
90
91 }
92
93 #endif