blob: d348ae92d4001cbce9c7acde829e6092f8b104e4 [file] [log] [blame]
Jonas Oreland09c452e2019-11-20 09:01:02 +01001/*
2 * Copyright 2019 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 "p2p/base/basic_ice_controller.h"
12
13namespace {
14
15// The minimum improvement in RTT that justifies a switch.
16const int kMinImprovement = 10;
17
18bool IsRelayRelay(const cricket::Connection* conn) {
19 return conn->local_candidate().type() == cricket::RELAY_PORT_TYPE &&
20 conn->remote_candidate().type() == cricket::RELAY_PORT_TYPE;
21}
22
23bool IsUdp(const cricket::Connection* conn) {
24 return conn->local_candidate().relay_protocol() == cricket::UDP_PROTOCOL_NAME;
25}
26
27// TODO(qingsi) Use an enum to replace the following constants for all
28// comparision results.
29static constexpr int a_is_better = 1;
30static constexpr int b_is_better = -1;
31static constexpr int a_and_b_equal = 0;
32
33bool LocalCandidateUsesPreferredNetwork(
34 const cricket::Connection* conn,
35 absl::optional<rtc::AdapterType> network_preference) {
36 rtc::AdapterType network_type = conn->port()->Network()->type();
37 return network_preference.has_value() && (network_type == network_preference);
38}
39
40int CompareCandidatePairsByNetworkPreference(
41 const cricket::Connection* a,
42 const cricket::Connection* b,
43 absl::optional<rtc::AdapterType> network_preference) {
44 bool a_uses_preferred_network =
45 LocalCandidateUsesPreferredNetwork(a, network_preference);
46 bool b_uses_preferred_network =
47 LocalCandidateUsesPreferredNetwork(b, network_preference);
48 if (a_uses_preferred_network && !b_uses_preferred_network) {
49 return a_is_better;
50 } else if (!a_uses_preferred_network && b_uses_preferred_network) {
51 return b_is_better;
52 }
53 return a_and_b_equal;
54}
55
56} // namespace
57
58namespace cricket {
59
60BasicIceController::BasicIceController(
61 std::function<IceTransportState()> ice_transport_state_func,
62 std::function<IceRole()> ice_role_func,
63 std::function<bool(const Connection*)> is_connection_pruned_func,
64 const IceFieldTrials* field_trials)
65 : ice_transport_state_func_(ice_transport_state_func),
66 ice_role_func_(ice_role_func),
67 is_connection_pruned_func_(is_connection_pruned_func),
68 field_trials_(field_trials) {}
69
70BasicIceController::~BasicIceController() {}
71
72void BasicIceController::SetIceConfig(const IceConfig& config) {
73 config_ = config;
74}
75
76void BasicIceController::SetSelectedConnection(
77 const Connection* selected_connection) {
78 selected_connection_ = selected_connection;
79}
80
81void BasicIceController::AddConnection(const Connection* connection) {
82 connections_.push_back(connection);
83 unpinged_connections_.insert(connection);
84}
85
86void BasicIceController::OnConnectionDestroyed(const Connection* connection) {
87 pinged_connections_.erase(connection);
88 unpinged_connections_.erase(connection);
89 connections_.erase(absl::c_find(connections_, connection));
90}
91
92bool BasicIceController::HasPingableConnection() const {
93 int64_t now = rtc::TimeMillis();
94 return absl::c_any_of(connections_, [this, now](const Connection* c) {
95 return IsPingable(c, now);
96 });
97}
98
99std::pair<Connection*, int> BasicIceController::SelectConnectionToPing(
100 int64_t last_ping_sent_ms) {
101 // When the selected connection is not receiving or not writable, or any
102 // active connection has not been pinged enough times, use the weak ping
103 // interval.
104 bool need_more_pings_at_weak_interval =
105 absl::c_any_of(connections_, [](const Connection* conn) {
106 return conn->active() &&
107 conn->num_pings_sent() < MIN_PINGS_AT_WEAK_PING_INTERVAL;
108 });
109 int ping_interval = (weak() || need_more_pings_at_weak_interval)
110 ? weak_ping_interval()
111 : strong_ping_interval();
112
113 const Connection* conn = nullptr;
114 if (rtc::TimeMillis() >= last_ping_sent_ms + ping_interval) {
115 conn = FindNextPingableConnection();
116 }
117 int delay = std::min(ping_interval, check_receiving_interval());
118 return std::make_pair(const_cast<Connection*>(conn), delay);
119}
120
121void BasicIceController::MarkConnectionPinged(const Connection* conn) {
122 if (conn && pinged_connections_.insert(conn).second) {
123 unpinged_connections_.erase(conn);
124 }
125}
126
127// Returns the next pingable connection to ping.
128const Connection* BasicIceController::FindNextPingableConnection() {
129 int64_t now = rtc::TimeMillis();
130
131 // Rule 1: Selected connection takes priority over non-selected ones.
132 if (selected_connection_ && selected_connection_->connected() &&
133 selected_connection_->writable() &&
134 WritableConnectionPastPingInterval(selected_connection_, now)) {
135 return selected_connection_;
136 }
137
138 // Rule 2: If the channel is weak, we need to find a new writable and
139 // receiving connection, probably on a different network. If there are lots of
140 // connections, it may take several seconds between two pings for every
141 // non-selected connection. This will cause the receiving state of those
142 // connections to be false, and thus they won't be selected. This is
143 // problematic for network fail-over. We want to make sure at least one
144 // connection per network is pinged frequently enough in order for it to be
145 // selectable. So we prioritize one connection per network.
146 // Rule 2.1: Among such connections, pick the one with the earliest
147 // last-ping-sent time.
148 if (weak()) {
149 std::vector<const Connection*> pingable_selectable_connections;
150 absl::c_copy_if(GetBestWritableConnectionPerNetwork(),
151 std::back_inserter(pingable_selectable_connections),
152 [this, now](const Connection* conn) {
153 return WritableConnectionPastPingInterval(conn, now);
154 });
155 auto iter = absl::c_min_element(
156 pingable_selectable_connections,
157 [](const Connection* conn1, const Connection* conn2) {
158 return conn1->last_ping_sent() < conn2->last_ping_sent();
159 });
160 if (iter != pingable_selectable_connections.end()) {
161 return *iter;
162 }
163 }
164
165 // Rule 3: Triggered checks have priority over non-triggered connections.
166 // Rule 3.1: Among triggered checks, oldest takes precedence.
167 const Connection* oldest_triggered_check =
168 FindOldestConnectionNeedingTriggeredCheck(now);
169 if (oldest_triggered_check) {
170 return oldest_triggered_check;
171 }
172
173 // Rule 4: Unpinged connections have priority over pinged ones.
174 RTC_CHECK(connections_.size() ==
175 pinged_connections_.size() + unpinged_connections_.size());
176 // If there are unpinged and pingable connections, only ping those.
177 // Otherwise, treat everything as unpinged.
178 // TODO(honghaiz): Instead of adding two separate vectors, we can add a state
179 // "pinged" to filter out unpinged connections.
180 if (absl::c_none_of(unpinged_connections_,
181 [this, now](const Connection* conn) {
182 return this->IsPingable(conn, now);
183 })) {
184 unpinged_connections_.insert(pinged_connections_.begin(),
185 pinged_connections_.end());
186 pinged_connections_.clear();
187 }
188
189 // Among un-pinged pingable connections, "more pingable" takes precedence.
190 std::vector<const Connection*> pingable_connections;
191 absl::c_copy_if(
192 unpinged_connections_, std::back_inserter(pingable_connections),
193 [this, now](const Connection* conn) { return IsPingable(conn, now); });
194 auto iter = absl::c_max_element(
195 pingable_connections,
196 [this](const Connection* conn1, const Connection* conn2) {
197 // Some implementations of max_element
198 // compare an element with itself.
199 if (conn1 == conn2) {
200 return false;
201 }
202 return MorePingable(conn1, conn2) == conn2;
203 });
204 if (iter != pingable_connections.end()) {
205 return *iter;
206 }
207 return nullptr;
208}
209
210// Find "triggered checks". We ping first those connections that have
211// received a ping but have not sent a ping since receiving it
212// (last_ping_received > last_ping_sent). But we shouldn't do
213// triggered checks if the connection is already writable.
214const Connection* BasicIceController::FindOldestConnectionNeedingTriggeredCheck(
215 int64_t now) {
216 const Connection* oldest_needing_triggered_check = nullptr;
217 for (auto* conn : connections_) {
218 if (!IsPingable(conn, now)) {
219 continue;
220 }
221 bool needs_triggered_check =
222 (!conn->writable() &&
223 conn->last_ping_received() > conn->last_ping_sent());
224 if (needs_triggered_check &&
225 (!oldest_needing_triggered_check ||
226 (conn->last_ping_received() <
227 oldest_needing_triggered_check->last_ping_received()))) {
228 oldest_needing_triggered_check = conn;
229 }
230 }
231
232 if (oldest_needing_triggered_check) {
233 RTC_LOG(LS_INFO) << "Selecting connection for triggered check: "
234 << oldest_needing_triggered_check->ToString();
235 }
236 return oldest_needing_triggered_check;
237}
238
239bool BasicIceController::WritableConnectionPastPingInterval(
240 const Connection* conn,
241 int64_t now) const {
242 int interval = CalculateActiveWritablePingInterval(conn, now);
243 return conn->last_ping_sent() + interval <= now;
244}
245
246int BasicIceController::CalculateActiveWritablePingInterval(
247 const Connection* conn,
248 int64_t now) const {
249 // Ping each connection at a higher rate at least
250 // MIN_PINGS_AT_WEAK_PING_INTERVAL times.
251 if (conn->num_pings_sent() < MIN_PINGS_AT_WEAK_PING_INTERVAL) {
252 return weak_ping_interval();
253 }
254
255 int stable_interval =
256 config_.stable_writable_connection_ping_interval_or_default();
257 int weak_or_stablizing_interval = std::min(
258 stable_interval, WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL);
259 // If the channel is weak or the connection is not stable yet, use the
260 // weak_or_stablizing_interval.
261 return (!weak() && conn->stable(now)) ? stable_interval
262 : weak_or_stablizing_interval;
263}
264
265// Is the connection in a state for us to even consider pinging the other side?
266// We consider a connection pingable even if it's not connected because that's
267// how a TCP connection is kicked into reconnecting on the active side.
268bool BasicIceController::IsPingable(const Connection* conn, int64_t now) const {
269 const Candidate& remote = conn->remote_candidate();
270 // We should never get this far with an empty remote ufrag.
271 RTC_DCHECK(!remote.username().empty());
272 if (remote.username().empty() || remote.password().empty()) {
273 // If we don't have an ICE ufrag and pwd, there's no way we can ping.
274 return false;
275 }
276
277 // A failed connection will not be pinged.
278 if (conn->state() == IceCandidatePairState::FAILED) {
279 return false;
280 }
281
282 // An never connected connection cannot be written to at all, so pinging is
283 // out of the question. However, if it has become WRITABLE, it is in the
284 // reconnecting state so ping is needed.
285 if (!conn->connected() && !conn->writable()) {
286 return false;
287 }
288
289 // If we sent a number of pings wo/ reply, skip sending more
290 // until we get one.
291 if (conn->TooManyOutstandingPings(field_trials_->max_outstanding_pings)) {
292 return false;
293 }
294
295 // If the channel is weakly connected, ping all connections.
296 if (weak()) {
297 return true;
298 }
299
300 // Always ping active connections regardless whether the channel is completed
301 // or not, but backup connections are pinged at a slower rate.
302 if (IsBackupConnection(conn)) {
303 return conn->rtt_samples() == 0 ||
304 (now >= conn->last_ping_response_received() +
305 config_.backup_connection_ping_interval_or_default());
306 }
307 // Don't ping inactive non-backup connections.
308 if (!conn->active()) {
309 return false;
310 }
311
312 // Do ping unwritable, active connections.
313 if (!conn->writable()) {
314 return true;
315 }
316
317 // Ping writable, active connections if it's been long enough since the last
318 // ping.
319 return WritableConnectionPastPingInterval(conn, now);
320}
321
322// A connection is considered a backup connection if the channel state
323// is completed, the connection is not the selected connection and it is active.
324bool BasicIceController::IsBackupConnection(const Connection* conn) const {
325 return ice_transport_state_func_() == IceTransportState::STATE_COMPLETED &&
326 conn != selected_connection_ && conn->active();
327}
328
329const Connection* BasicIceController::MorePingable(const Connection* conn1,
330 const Connection* conn2) {
331 RTC_DCHECK(conn1 != conn2);
332 if (config_.prioritize_most_likely_candidate_pairs) {
333 const Connection* most_likely_to_work_conn = MostLikelyToWork(conn1, conn2);
334 if (most_likely_to_work_conn) {
335 return most_likely_to_work_conn;
336 }
337 }
338
339 const Connection* least_recently_pinged_conn =
340 LeastRecentlyPinged(conn1, conn2);
341 if (least_recently_pinged_conn) {
342 return least_recently_pinged_conn;
343 }
344
345 // During the initial state when nothing has been pinged yet, return the first
346 // one in the ordered |connections_|.
347 auto connections = connections_;
348 return *(std::find_if(connections.begin(), connections.end(),
349 [conn1, conn2](const Connection* conn) {
350 return conn == conn1 || conn == conn2;
351 }));
352}
353
354const Connection* BasicIceController::MostLikelyToWork(
355 const Connection* conn1,
356 const Connection* conn2) {
357 bool rr1 = IsRelayRelay(conn1);
358 bool rr2 = IsRelayRelay(conn2);
359 if (rr1 && !rr2) {
360 return conn1;
361 } else if (rr2 && !rr1) {
362 return conn2;
363 } else if (rr1 && rr2) {
364 bool udp1 = IsUdp(conn1);
365 bool udp2 = IsUdp(conn2);
366 if (udp1 && !udp2) {
367 return conn1;
368 } else if (udp2 && udp1) {
369 return conn2;
370 }
371 }
372 return nullptr;
373}
374
375const Connection* BasicIceController::LeastRecentlyPinged(
376 const Connection* conn1,
377 const Connection* conn2) {
378 if (conn1->last_ping_sent() < conn2->last_ping_sent()) {
379 return conn1;
380 }
381 if (conn1->last_ping_sent() > conn2->last_ping_sent()) {
382 return conn2;
383 }
384 return nullptr;
385}
386
387std::map<rtc::Network*, const Connection*>
388BasicIceController::GetBestConnectionByNetwork() const {
389 // |connections_| has been sorted, so the first one in the list on a given
390 // network is the best connection on the network, except that the selected
391 // connection is always the best connection on the network.
392 std::map<rtc::Network*, const Connection*> best_connection_by_network;
393 if (selected_connection_) {
394 best_connection_by_network[selected_connection_->port()->Network()] =
395 selected_connection_;
396 }
397 // TODO(honghaiz): Need to update this if |connections_| are not sorted.
398 for (const Connection* conn : connections_) {
399 rtc::Network* network = conn->port()->Network();
400 // This only inserts when the network does not exist in the map.
401 best_connection_by_network.insert(std::make_pair(network, conn));
402 }
403 return best_connection_by_network;
404}
405
406std::vector<const Connection*>
407BasicIceController::GetBestWritableConnectionPerNetwork() const {
408 std::vector<const Connection*> connections;
409 for (auto kv : GetBestConnectionByNetwork()) {
410 const Connection* conn = kv.second;
411 if (conn->writable() && conn->connected()) {
412 connections.push_back(conn);
413 }
414 }
415 return connections;
416}
417
418IceControllerInterface::SwitchResult
419BasicIceController::HandleInitialSelectDampening(
420 IceControllerEvent reason,
421 const Connection* new_connection) {
422 if (!field_trials_->initial_select_dampening.has_value() &&
423 !field_trials_->initial_select_dampening_ping_received.has_value()) {
424 // experiment not enabled => select connection.
425 return {new_connection, absl::nullopt};
426 }
427
428 int64_t now = rtc::TimeMillis();
429 int64_t max_delay = 0;
430 if (new_connection->last_ping_received() > 0 &&
431 field_trials_->initial_select_dampening_ping_received.has_value()) {
432 max_delay = *field_trials_->initial_select_dampening_ping_received;
433 } else if (field_trials_->initial_select_dampening.has_value()) {
434 max_delay = *field_trials_->initial_select_dampening;
435 }
436
437 int64_t start_wait =
438 initial_select_timestamp_ms_ == 0 ? now : initial_select_timestamp_ms_;
439 int64_t max_wait_until = start_wait + max_delay;
440
441 if (now >= max_wait_until) {
442 RTC_LOG(LS_INFO) << "reset initial_select_timestamp_ = "
443 << initial_select_timestamp_ms_
444 << " selection delayed by: " << (now - start_wait) << "ms";
445 initial_select_timestamp_ms_ = 0;
446 return {new_connection, absl::nullopt};
447 }
448
449 // We are not yet ready to select first connection...
450 if (initial_select_timestamp_ms_ == 0) {
451 // Set timestamp on first time...
452 // but run the delayed invokation everytime to
453 // avoid possibility that we miss it.
454 initial_select_timestamp_ms_ = now;
455 RTC_LOG(LS_INFO) << "set initial_select_timestamp_ms_ = "
456 << initial_select_timestamp_ms_;
457 }
458
459 int min_delay = max_delay;
460 if (field_trials_->initial_select_dampening.has_value()) {
461 min_delay = std::min(min_delay, *field_trials_->initial_select_dampening);
462 }
463 if (field_trials_->initial_select_dampening_ping_received.has_value()) {
464 min_delay = std::min(
465 min_delay, *field_trials_->initial_select_dampening_ping_received);
466 }
467
468 RTC_LOG(LS_INFO) << "delay initial selection up to " << min_delay << "ms";
469 return {absl::nullopt, min_delay};
470}
471
472IceControllerInterface::SwitchResult BasicIceController::ShouldSwitchConnection(
473 IceControllerEvent reason,
474 const Connection* new_connection) {
475 if (!ReadyToSend(new_connection) || selected_connection_ == new_connection) {
476 return {absl::nullopt, absl::nullopt};
477 }
478
479 if (selected_connection_ == nullptr) {
480 return HandleInitialSelectDampening(reason, new_connection);
481 }
482
483 // Do not switch to a connection that is not receiving if it is not on a
484 // preferred network or it has higher cost because it may be just spuriously
485 // better.
486 int compare_a_b_by_networks = CompareCandidatePairNetworks(
487 new_connection, selected_connection_, config_.network_preference);
488 if (compare_a_b_by_networks == b_is_better && !new_connection->receiving()) {
489 return {absl::nullopt, absl::nullopt};
490 }
491
492 bool missed_receiving_unchanged_threshold = false;
493 absl::optional<int64_t> receiving_unchanged_threshold(
494 rtc::TimeMillis() - config_.receiving_switching_delay_or_default());
495 int cmp = CompareConnections(selected_connection_, new_connection,
496 receiving_unchanged_threshold,
497 &missed_receiving_unchanged_threshold);
498
499 absl::optional<int> recheck_delay;
500 if (missed_receiving_unchanged_threshold &&
501 config_.receiving_switching_delay_or_default()) {
502 // If we do not switch to the connection because it missed the receiving
503 // threshold, the new connection is in a better receiving state than the
504 // currently selected connection. So we need to re-check whether it needs
505 // to be switched at a later time.
506 recheck_delay = config_.receiving_switching_delay_or_default();
507 }
508
509 if (cmp < 0) {
510 return {new_connection, absl::nullopt};
511 } else if (cmp > 0) {
512 return {absl::nullopt, recheck_delay};
513 }
514
515 // If everything else is the same, switch only if rtt has improved by
516 // a margin.
517 if (new_connection->rtt() <= selected_connection_->rtt() - kMinImprovement) {
518 return {new_connection, absl::nullopt};
519 }
520
521 return {absl::nullopt, recheck_delay};
522}
523
524IceControllerInterface::SwitchResult
525BasicIceController::SortAndSwitchConnection(IceControllerEvent reason) {
526 // Find the best alternative connection by sorting. It is important to note
527 // that amongst equal preference, writable connections, this will choose the
528 // one whose estimated latency is lowest. So it is the only one that we
529 // need to consider switching to.
530 // TODO(honghaiz): Don't sort; Just use std::max_element in the right places.
531 absl::c_stable_sort(
532 connections_, [this](const Connection* a, const Connection* b) {
533 int cmp = CompareConnections(a, b, absl::nullopt, nullptr);
534 if (cmp != 0) {
535 return cmp > 0;
536 }
537 // Otherwise, sort based on latency estimate.
538 return a->rtt() < b->rtt();
539 });
540
541 RTC_LOG(LS_VERBOSE) << "Sorting " << connections_.size()
542 << " available connections";
543 for (size_t i = 0; i < connections_.size(); ++i) {
544 RTC_LOG(LS_VERBOSE) << connections_[i]->ToString();
545 }
546
547 const Connection* top_connection =
548 (!connections_.empty()) ? connections_[0] : nullptr;
549
550 return ShouldSwitchConnection(reason, top_connection);
551}
552
553bool BasicIceController::ReadyToSend(const Connection* connection) const {
554 // Note that we allow sending on an unreliable connection, because it's
555 // possible that it became unreliable simply due to bad chance.
556 // So this shouldn't prevent attempting to send media.
557 return connection != nullptr &&
558 (connection->writable() ||
559 connection->write_state() == Connection::STATE_WRITE_UNRELIABLE ||
560 PresumedWritable(connection));
561}
562
563bool BasicIceController::PresumedWritable(const Connection* conn) const {
564 return (conn->write_state() == Connection::STATE_WRITE_INIT &&
565 config_.presume_writable_when_fully_relayed &&
566 conn->local_candidate().type() == RELAY_PORT_TYPE &&
567 (conn->remote_candidate().type() == RELAY_PORT_TYPE ||
568 conn->remote_candidate().type() == PRFLX_PORT_TYPE));
569}
570
571// Compare two connections based on their writing, receiving, and connected
572// states.
573int BasicIceController::CompareConnectionStates(
574 const Connection* a,
575 const Connection* b,
576 absl::optional<int64_t> receiving_unchanged_threshold,
577 bool* missed_receiving_unchanged_threshold) const {
578 // First, prefer a connection that's writable or presumed writable over
579 // one that's not writable.
580 bool a_writable = a->writable() || PresumedWritable(a);
581 bool b_writable = b->writable() || PresumedWritable(b);
582 if (a_writable && !b_writable) {
583 return a_is_better;
584 }
585 if (!a_writable && b_writable) {
586 return b_is_better;
587 }
588
589 // Sort based on write-state. Better states have lower values.
590 if (a->write_state() < b->write_state()) {
591 return a_is_better;
592 }
593 if (b->write_state() < a->write_state()) {
594 return b_is_better;
595 }
596
597 // We prefer a receiving connection to a non-receiving, higher-priority
598 // connection when sorting connections and choosing which connection to
599 // switch to.
600 if (a->receiving() && !b->receiving()) {
601 return a_is_better;
602 }
603 if (!a->receiving() && b->receiving()) {
604 if (!receiving_unchanged_threshold ||
605 (a->receiving_unchanged_since() <= *receiving_unchanged_threshold &&
606 b->receiving_unchanged_since() <= *receiving_unchanged_threshold)) {
607 return b_is_better;
608 }
609 *missed_receiving_unchanged_threshold = true;
610 }
611
612 // WARNING: Some complexity here about TCP reconnecting.
613 // When a TCP connection fails because of a TCP socket disconnecting, the
614 // active side of the connection will attempt to reconnect for 5 seconds while
615 // pretending to be writable (the connection is not set to the unwritable
616 // state). On the passive side, the connection also remains writable even
617 // though it is disconnected, and a new connection is created when the active
618 // side connects. At that point, there are two TCP connections on the passive
619 // side: 1. the old, disconnected one that is pretending to be writable, and
620 // 2. the new, connected one that is maybe not yet writable. For purposes of
621 // pruning, pinging, and selecting the selected connection, we want to treat
622 // the new connection as "better" than the old one. We could add a method
623 // called something like Connection::ImReallyBadEvenThoughImWritable, but that
624 // is equivalent to the existing Connection::connected(), which we already
625 // have. So, in code throughout this file, we'll check whether the connection
626 // is connected() or not, and if it is not, treat it as "worse" than a
627 // connected one, even though it's writable. In the code below, we're doing
628 // so to make sure we treat a new writable connection as better than an old
629 // disconnected connection.
630
631 // In the case where we reconnect TCP connections, the original best
632 // connection is disconnected without changing to WRITE_TIMEOUT. In this case,
633 // the new connection, when it becomes writable, should have higher priority.
634 if (a->write_state() == Connection::STATE_WRITABLE &&
635 b->write_state() == Connection::STATE_WRITABLE) {
636 if (a->connected() && !b->connected()) {
637 return a_is_better;
638 }
639 if (!a->connected() && b->connected()) {
640 return b_is_better;
641 }
642 }
643
644 return 0;
645}
646
647// Compares two connections based only on the candidate and network information.
648// Returns positive if |a| is better than |b|.
649int BasicIceController::CompareConnectionCandidates(const Connection* a,
650 const Connection* b) const {
651 int compare_a_b_by_networks =
652 CompareCandidatePairNetworks(a, b, config_.network_preference);
653 if (compare_a_b_by_networks != a_and_b_equal) {
654 return compare_a_b_by_networks;
655 }
656
657 // Compare connection priority. Lower values get sorted last.
658 if (a->priority() > b->priority()) {
659 return a_is_better;
660 }
661 if (a->priority() < b->priority()) {
662 return b_is_better;
663 }
664
665 // If we're still tied at this point, prefer a younger generation.
666 // (Younger generation means a larger generation number).
667 int cmp = (a->remote_candidate().generation() + a->port()->generation()) -
668 (b->remote_candidate().generation() + b->port()->generation());
669 if (cmp != 0) {
670 return cmp;
671 }
672
673 // A periodic regather (triggered by the regather_all_networks_interval_range)
674 // will produce candidates that appear the same but would use a new port. We
675 // want to use the new candidates and purge the old candidates as they come
676 // in, so use the fact that the old ports get pruned immediately to rank the
677 // candidates with an active port/remote candidate higher.
678 bool a_pruned = is_connection_pruned_func_(a);
679 bool b_pruned = is_connection_pruned_func_(b);
680 if (!a_pruned && b_pruned) {
681 return a_is_better;
682 }
683 if (a_pruned && !b_pruned) {
684 return b_is_better;
685 }
686
687 // Otherwise, must be equal
688 return 0;
689}
690
691int BasicIceController::CompareConnections(
692 const Connection* a,
693 const Connection* b,
694 absl::optional<int64_t> receiving_unchanged_threshold,
695 bool* missed_receiving_unchanged_threshold) const {
696 RTC_CHECK(a != nullptr);
697 RTC_CHECK(b != nullptr);
698
699 // We prefer to switch to a writable and receiving connection over a
700 // non-writable or non-receiving connection, even if the latter has
701 // been nominated by the controlling side.
702 int state_cmp = CompareConnectionStates(a, b, receiving_unchanged_threshold,
703 missed_receiving_unchanged_threshold);
704 if (state_cmp != 0) {
705 return state_cmp;
706 }
707
708 if (ice_role_func_() == ICEROLE_CONTROLLED) {
709 // Compare the connections based on the nomination states and the last data
710 // received time if this is on the controlled side.
711 if (a->remote_nomination() > b->remote_nomination()) {
712 return a_is_better;
713 }
714 if (a->remote_nomination() < b->remote_nomination()) {
715 return b_is_better;
716 }
717
718 if (a->last_data_received() > b->last_data_received()) {
719 return a_is_better;
720 }
721 if (a->last_data_received() < b->last_data_received()) {
722 return b_is_better;
723 }
724 }
725
726 // Compare the network cost and priority.
727 return CompareConnectionCandidates(a, b);
728}
729
730int BasicIceController::CompareCandidatePairNetworks(
731 const Connection* a,
732 const Connection* b,
733 absl::optional<rtc::AdapterType> network_preference) const {
734 int compare_a_b_by_network_preference =
735 CompareCandidatePairsByNetworkPreference(a, b,
736 config_.network_preference);
737 // The network preference has a higher precedence than the network cost.
738 if (compare_a_b_by_network_preference != a_and_b_equal) {
739 return compare_a_b_by_network_preference;
740 }
741
742 uint32_t a_cost = a->ComputeNetworkCost();
743 uint32_t b_cost = b->ComputeNetworkCost();
744 // Prefer lower network cost.
745 if (a_cost < b_cost) {
746 return a_is_better;
747 }
748 if (a_cost > b_cost) {
749 return b_is_better;
750 }
751 return a_and_b_equal;
752}
753
754std::vector<const Connection*> BasicIceController::PruneConnections() {
755 // We can prune any connection for which there is a connected, writable
756 // connection on the same network with better or equal priority. We leave
757 // those with better priority just in case they become writable later (at
758 // which point, we would prune out the current selected connection). We leave
759 // connections on other networks because they may not be using the same
760 // resources and they may represent very distinct paths over which we can
761 // switch. If |best_conn_on_network| is not connected, we may be reconnecting
762 // a TCP connection and should not prune connections in this network.
763 // See the big comment in CompareConnectionStates.
764 //
765 // An exception is made for connections on an "any address" network, meaning
766 // not bound to any specific network interface. We don't want to keep one of
767 // these alive as a backup, since it could be using the same network
768 // interface as the higher-priority, selected candidate pair.
769 std::vector<const Connection*> connections_to_prune;
770 auto best_connection_by_network = GetBestConnectionByNetwork();
771 for (const Connection* conn : connections_) {
772 const Connection* best_conn = selected_connection_;
773 if (!rtc::IPIsAny(conn->port()->Network()->ip())) {
774 // If the connection is bound to a specific network interface (not an
775 // "any address" network), compare it against the best connection for
776 // that network interface rather than the best connection overall. This
777 // ensures that at least one connection per network will be left
778 // unpruned.
779 best_conn = best_connection_by_network[conn->port()->Network()];
780 }
781 // Do not prune connections if the connection being compared against is
782 // weak. Otherwise, it may delete connections prematurely.
783 if (best_conn && conn != best_conn && !best_conn->weak() &&
784 CompareConnectionCandidates(best_conn, conn) >= 0) {
785 connections_to_prune.push_back(conn);
786 }
787 }
788 return connections_to_prune;
789}
790
791bool BasicIceController::GetUseCandidateAttr(const Connection* conn,
792 NominationMode mode,
793 IceMode remote_ice_mode) const {
794 switch (mode) {
795 case NominationMode::REGULAR:
796 // TODO(honghaiz): Implement regular nomination.
797 return false;
798 case NominationMode::AGGRESSIVE:
799 if (remote_ice_mode == ICEMODE_LITE) {
800 return GetUseCandidateAttr(conn, NominationMode::REGULAR,
801 remote_ice_mode);
802 }
803 return true;
804 case NominationMode::SEMI_AGGRESSIVE: {
805 // Nominate if
806 // a) Remote is in FULL ICE AND
807 // a.1) |conn| is the selected connection OR
808 // a.2) there is no selected connection OR
809 // a.3) the selected connection is unwritable OR
810 // a.4) |conn| has higher priority than selected_connection.
811 // b) Remote is in LITE ICE AND
812 // b.1) |conn| is the selected_connection AND
813 // b.2) |conn| is writable.
814 bool selected = conn == selected_connection_;
815 if (remote_ice_mode == ICEMODE_LITE) {
816 return selected && conn->writable();
817 }
818 bool better_than_selected =
819 !selected_connection_ || !selected_connection_->writable() ||
820 CompareConnectionCandidates(selected_connection_, conn) < 0;
821 return selected || better_than_selected;
822 }
823 default:
824 RTC_NOTREACHED();
825 return false;
826 }
827}
828
829} // namespace cricket