blob: a8c962af21ae551b67f387763fe116b8cceaaaa8 [file] [log] [blame]
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +02001/*
2 * Copyright 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "call/simulated_network.h"
12
13#include <algorithm>
14#include <cmath>
15#include <utility>
Yves Gerey3e707812018-11-28 16:47:49 +010016
Sebastian Jansson2cd3b4c2018-11-06 19:18:28 +010017#include "api/units/data_rate.h"
Yves Gerey3e707812018-11-28 16:47:49 +010018#include "api/units/data_size.h"
19#include "api/units/time_delta.h"
20#include "rtc_base/checks.h"
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +020021
22namespace webrtc {
Sebastian Jansson836fee12019-02-08 16:08:10 +010023namespace {
Sebastian Jansson2b08e312019-02-25 10:24:46 +010024constexpr TimeDelta kDefaultProcessDelay = TimeDelta::Millis<5>();
25} // namespace
26
27CoDelSimulation::CoDelSimulation() = default;
28CoDelSimulation::~CoDelSimulation() = default;
29
30bool CoDelSimulation::DropDequeuedPacket(Timestamp now,
31 Timestamp enqueing_time,
32 DataSize packet_size,
33 DataSize queue_size) {
34 constexpr TimeDelta kWindow = TimeDelta::Millis<100>();
35 constexpr TimeDelta kDelayThreshold = TimeDelta::Millis<5>();
36 constexpr TimeDelta kDropCountMemory = TimeDelta::Millis<1600>();
37 constexpr DataSize kMaxPacketSize = DataSize::Bytes<1500>();
38
39 // Compensates for process interval in simulation; not part of standard CoDel.
40 TimeDelta queuing_time = now - enqueing_time - kDefaultProcessDelay;
41
42 if (queue_size < kMaxPacketSize || queuing_time < kDelayThreshold) {
43 enter_drop_state_at_ = Timestamp::PlusInfinity();
44 state_ = kNormal;
45 return false;
46 }
47 switch (state_) {
48 case kNormal:
49 enter_drop_state_at_ = now + kWindow;
50 state_ = kPending;
51 return false;
52
53 case kPending:
54 if (now >= enter_drop_state_at_) {
55 state_ = kDropping;
56 // Starting the drop counter with the drops made during the most recent
57 // drop state period.
58 drop_count_ = drop_count_ - previous_drop_count_;
59 if (now >= last_drop_at_ + kDropCountMemory)
60 drop_count_ = 0;
61 previous_drop_count_ = drop_count_;
62 last_drop_at_ = now;
63 ++drop_count_;
64 return true;
65 }
66 return false;
67
68 case kDropping:
69 TimeDelta drop_delay = kWindow / sqrt(static_cast<double>(drop_count_));
70 Timestamp next_drop_at = last_drop_at_ + drop_delay;
71 if (now >= next_drop_at) {
72 if (queue_size - packet_size < kMaxPacketSize)
73 state_ = kPending;
74 last_drop_at_ = next_drop_at;
75 ++drop_count_;
76 return true;
77 }
78 return false;
79 }
Sebastian Jansson836fee12019-02-08 16:08:10 +010080}
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +020081
82SimulatedNetwork::SimulatedNetwork(SimulatedNetwork::Config config,
83 uint64_t random_seed)
84 : random_(random_seed), bursting_(false) {
85 SetConfig(config);
86}
87
88SimulatedNetwork::~SimulatedNetwork() = default;
89
90void SimulatedNetwork::SetConfig(const SimulatedNetwork::Config& config) {
91 rtc::CritScope crit(&config_lock_);
Sebastian Janssoneceea312019-01-31 11:50:04 +010092 config_state_.config = config; // Shallow copy of the struct.
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +020093 double prob_loss = config.loss_percent / 100.0;
Sebastian Janssoneceea312019-01-31 11:50:04 +010094 if (config_state_.config.avg_burst_loss_length == -1) {
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +020095 // Uniform loss
Sebastian Janssoneceea312019-01-31 11:50:04 +010096 config_state_.prob_loss_bursting = prob_loss;
97 config_state_.prob_start_bursting = prob_loss;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +020098 } else {
99 // Lose packets according to a gilbert-elliot model.
100 int avg_burst_loss_length = config.avg_burst_loss_length;
101 int min_avg_burst_loss_length = std::ceil(prob_loss / (1 - prob_loss));
102
103 RTC_CHECK_GT(avg_burst_loss_length, min_avg_burst_loss_length)
104 << "For a total packet loss of " << config.loss_percent << "%% then"
105 << " avg_burst_loss_length must be " << min_avg_burst_loss_length + 1
106 << " or higher.";
107
Sebastian Janssoneceea312019-01-31 11:50:04 +0100108 config_state_.prob_loss_bursting = (1.0 - 1.0 / avg_burst_loss_length);
109 config_state_.prob_start_bursting =
110 prob_loss / (1 - prob_loss) / avg_burst_loss_length;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200111 }
112}
113
114void SimulatedNetwork::PauseTransmissionUntil(int64_t until_us) {
115 rtc::CritScope crit(&config_lock_);
Sebastian Janssoneceea312019-01-31 11:50:04 +0100116 config_state_.pause_transmission_until_us = until_us;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200117}
118
119bool SimulatedNetwork::EnqueuePacket(PacketInFlightInfo packet) {
Sebastian Janssoneceea312019-01-31 11:50:04 +0100120 RTC_DCHECK_RUNS_SERIALIZED(&process_checker_);
121 ConfigState state = GetConfigState();
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100122
Sebastian Janssoneceea312019-01-31 11:50:04 +0100123 UpdateCapacityQueue(state, packet.send_time_us);
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100124
Sebastian Janssoneceea312019-01-31 11:50:04 +0100125 packet.size += state.config.packet_overhead;
126
127 if (state.config.queue_length_packets > 0 &&
128 capacity_link_.size() >= state.config.queue_length_packets) {
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200129 // Too many packet on the link, drop this one.
130 return false;
131 }
Sebastian Jansson2cd3b4c2018-11-06 19:18:28 +0100132
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100133 // Set arrival time = send time for now; actual arrival time will be
134 // calculated in UpdateCapacityQueue.
135 queue_size_bytes_ += packet.size;
136 capacity_link_.push({packet, packet.send_time_us});
Sebastian Jansson836fee12019-02-08 16:08:10 +0100137 if (!next_process_time_us_) {
Sebastian Jansson2b08e312019-02-25 10:24:46 +0100138 next_process_time_us_ = packet.send_time_us + kDefaultProcessDelay.us();
Sebastian Jansson836fee12019-02-08 16:08:10 +0100139 }
Sebastian Jansson2cd3b4c2018-11-06 19:18:28 +0100140
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200141 return true;
142}
143
144absl::optional<int64_t> SimulatedNetwork::NextDeliveryTimeUs() const {
Sebastian Janssoneceea312019-01-31 11:50:04 +0100145 RTC_DCHECK_RUNS_SERIALIZED(&process_checker_);
Sebastian Jansson836fee12019-02-08 16:08:10 +0100146 return next_process_time_us_;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200147}
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100148
Sebastian Janssoneceea312019-01-31 11:50:04 +0100149void SimulatedNetwork::UpdateCapacityQueue(ConfigState state,
150 int64_t time_now_us) {
151 bool needs_sort = false;
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100152
Sebastian Janssoneceea312019-01-31 11:50:04 +0100153 // Catch for thread races.
154 if (time_now_us < last_capacity_link_visit_us_.value_or(time_now_us))
155 return;
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100156
Sebastian Janssoneceea312019-01-31 11:50:04 +0100157 int64_t time_us = last_capacity_link_visit_us_.value_or(time_now_us);
158 // Check the capacity link first.
159 while (!capacity_link_.empty()) {
160 int64_t time_until_front_exits_us = 0;
161 if (state.config.link_capacity_kbps > 0) {
162 int64_t remaining_bits =
163 capacity_link_.front().packet.size * 8 - pending_drain_bits_;
164 RTC_DCHECK(remaining_bits > 0);
165 // Division rounded up - packet not delivered until its last bit is.
166 time_until_front_exits_us =
167 (1000 * remaining_bits + state.config.link_capacity_kbps - 1) /
168 state.config.link_capacity_kbps;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200169 }
170
Sebastian Janssoneceea312019-01-31 11:50:04 +0100171 if (time_us + time_until_front_exits_us > time_now_us) {
172 // Packet at front will not exit yet. Will not enter here on infinite
173 // capacity(=0) so no special handling needed.
174 pending_drain_bits_ +=
175 ((time_now_us - time_us) * state.config.link_capacity_kbps) / 1000;
176 break;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200177 }
Sebastian Janssoneceea312019-01-31 11:50:04 +0100178 if (state.config.link_capacity_kbps > 0) {
179 pending_drain_bits_ +=
180 (time_until_front_exits_us * state.config.link_capacity_kbps) / 1000;
181 } else {
182 // Enough to drain the whole queue.
183 pending_drain_bits_ = queue_size_bytes_ * 8;
184 }
185
186 // Time to get this packet.
Mirko Bonadei05cf6be2019-01-31 21:38:12 +0100187 PacketInfo packet = capacity_link_.front();
Sebastian Janssoneceea312019-01-31 11:50:04 +0100188 capacity_link_.pop();
189
190 time_us += time_until_front_exits_us;
Sebastian Jansson2b08e312019-02-25 10:24:46 +0100191 if (state.config.codel_active_queue_management) {
192 while (!capacity_link_.empty() &&
193 codel_controller_.DropDequeuedPacket(
194 Timestamp::us(time_us),
195 Timestamp::us(capacity_link_.front().packet.send_time_us),
196 DataSize::bytes(capacity_link_.front().packet.size),
197 DataSize::bytes(queue_size_bytes_))) {
198 PacketInfo dropped = capacity_link_.front();
199 capacity_link_.pop();
200 queue_size_bytes_ -= dropped.packet.size;
201 dropped.arrival_time_us = PacketDeliveryInfo::kNotReceived;
202 delay_link_.emplace_back(dropped);
203 }
204 }
Sebastian Janssoneceea312019-01-31 11:50:04 +0100205 RTC_DCHECK(time_us >= packet.packet.send_time_us);
206 packet.arrival_time_us =
207 std::max(state.pause_transmission_until_us, time_us);
208 queue_size_bytes_ -= packet.packet.size;
209 pending_drain_bits_ -= packet.packet.size * 8;
210 RTC_DCHECK(pending_drain_bits_ >= 0);
211
212 // Drop packets at an average rate of |state.config.loss_percent| with
213 // and average loss burst length of |state.config.avg_burst_loss_length|.
214 if ((bursting_ && random_.Rand<double>() < state.prob_loss_bursting) ||
215 (!bursting_ && random_.Rand<double>() < state.prob_start_bursting)) {
216 bursting_ = true;
217 packet.arrival_time_us = PacketDeliveryInfo::kNotReceived;
218 } else {
219 bursting_ = false;
220 int64_t arrival_time_jitter_us = std::max(
221 random_.Gaussian(state.config.queue_delay_ms * 1000,
222 state.config.delay_standard_deviation_ms * 1000),
223 0.0);
224
225 // If reordering is not allowed then adjust arrival_time_jitter
226 // to make sure all packets are sent in order.
227 int64_t last_arrival_time_us =
228 delay_link_.empty() ? -1 : delay_link_.back().arrival_time_us;
229 if (!state.config.allow_reordering && !delay_link_.empty() &&
230 packet.arrival_time_us + arrival_time_jitter_us <
231 last_arrival_time_us) {
232 arrival_time_jitter_us = last_arrival_time_us - packet.arrival_time_us;
233 }
234 packet.arrival_time_us += arrival_time_jitter_us;
235 if (packet.arrival_time_us >= last_arrival_time_us) {
236 last_arrival_time_us = packet.arrival_time_us;
237 } else {
238 needs_sort = true;
239 }
240 }
Mirko Bonadei05cf6be2019-01-31 21:38:12 +0100241 delay_link_.emplace_back(packet);
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200242 }
Sebastian Janssoneceea312019-01-31 11:50:04 +0100243 last_capacity_link_visit_us_ = time_now_us;
244 // Cannot save unused capacity for later.
245 pending_drain_bits_ = std::min(pending_drain_bits_, queue_size_bytes_ * 8);
246
247 if (needs_sort) {
248 // Packet(s) arrived out of order, make sure list is sorted.
249 std::sort(delay_link_.begin(), delay_link_.end(),
250 [](const PacketInfo& p1, const PacketInfo& p2) {
251 return p1.arrival_time_us < p2.arrival_time_us;
252 });
253 }
254}
255
256SimulatedNetwork::ConfigState SimulatedNetwork::GetConfigState() const {
257 rtc::CritScope crit(&config_lock_);
258 return config_state_;
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200259}
260
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100261std::vector<PacketDeliveryInfo> SimulatedNetwork::DequeueDeliverablePackets(
262 int64_t receive_time_us) {
Sebastian Janssoneceea312019-01-31 11:50:04 +0100263 RTC_DCHECK_RUNS_SERIALIZED(&process_checker_);
264 UpdateCapacityQueue(GetConfigState(), receive_time_us);
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100265 std::vector<PacketDeliveryInfo> packets_to_deliver;
266 // Check the extra delay queue.
267 while (!delay_link_.empty() &&
268 receive_time_us >= delay_link_.front().arrival_time_us) {
269 PacketInfo packet_info = delay_link_.front();
270 packets_to_deliver.emplace_back(
271 PacketDeliveryInfo(packet_info.packet, packet_info.arrival_time_us));
272 delay_link_.pop_front();
273 }
Sebastian Jansson836fee12019-02-08 16:08:10 +0100274
275 if (!delay_link_.empty()) {
276 next_process_time_us_ = delay_link_.front().arrival_time_us;
277 } else if (!capacity_link_.empty()) {
Sebastian Jansson2b08e312019-02-25 10:24:46 +0100278 next_process_time_us_ = receive_time_us + kDefaultProcessDelay.us();
Sebastian Jansson836fee12019-02-08 16:08:10 +0100279 } else {
280 next_process_time_us_.reset();
281 }
Christoffer Rodbro813c79b2019-01-31 09:25:12 +0100282 return packets_to_deliver;
283}
284
Sebastian Janssonf96b1ca2018-08-07 18:58:05 +0200285} // namespace webrtc