blob: b8e774a0be11870bc5f5c9e438c04084a4c70b8c [file] [log] [blame]
philipel863a8262016-06-17 09:21:34 -07001/*
2 * Copyright (c) 2016 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 "webrtc/modules/congestion_controller/delay_based_bwe.h"
12
13#include <math.h>
14
15#include <algorithm>
16
17#include "webrtc/base/checks.h"
18#include "webrtc/base/constructormagic.h"
19#include "webrtc/base/logging.h"
20#include "webrtc/base/thread_annotations.h"
21#include "webrtc/modules/pacing/paced_sender.h"
22#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
23#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
24#include "webrtc/typedefs.h"
25
26namespace {
27enum {
28 kTimestampGroupLengthMs = 5,
29 kAbsSendTimeFraction = 18,
30 kAbsSendTimeInterArrivalUpshift = 8,
31 kInterArrivalShift = kAbsSendTimeFraction + kAbsSendTimeInterArrivalUpshift,
32 kInitialProbingIntervalMs = 2000,
33 kMinClusterSize = 4,
34 kMaxProbePackets = 15,
35 kExpectedNumberOfProbes = 3
36};
37
38static const double kTimestampToMs =
39 1000.0 / static_cast<double>(1 << kInterArrivalShift);
40
41template <typename K, typename V>
42std::vector<K> Keys(const std::map<K, V>& map) {
43 std::vector<K> keys;
44 keys.reserve(map.size());
45 for (typename std::map<K, V>::const_iterator it = map.begin();
46 it != map.end(); ++it) {
47 keys.push_back(it->first);
48 }
49 return keys;
50}
51
52uint32_t ConvertMsTo24Bits(int64_t time_ms) {
53 uint32_t time_24_bits =
54 static_cast<uint32_t>(
55 ((static_cast<uint64_t>(time_ms) << kAbsSendTimeFraction) + 500) /
56 1000) &
57 0x00FFFFFF;
58 return time_24_bits;
59}
60} // namespace
61
62namespace webrtc {
63
64void DelayBasedBwe::AddCluster(std::list<Cluster>* clusters, Cluster* cluster) {
65 cluster->send_mean_ms /= static_cast<float>(cluster->count);
66 cluster->recv_mean_ms /= static_cast<float>(cluster->count);
67 cluster->mean_size /= cluster->count;
68 clusters->push_back(*cluster);
69}
70
stefan5e12d362016-07-11 01:44:02 -070071DelayBasedBwe::DelayBasedBwe(RemoteBitrateObserver* observer, Clock* clock)
72 : clock_(clock),
73 observer_(observer),
philipel863a8262016-06-17 09:21:34 -070074 inter_arrival_(),
75 estimator_(),
76 detector_(OverUseDetectorOptions()),
77 incoming_bitrate_(kBitrateWindowMs, 8000),
78 total_probes_received_(0),
79 first_packet_time_ms_(-1),
80 last_update_ms_(-1),
81 ssrcs_() {
82 RTC_DCHECK(observer_);
83 // NOTE! The BitrateEstimatorTest relies on this EXACT log line.
84 LOG(LS_INFO) << "RemoteBitrateEstimatorAbsSendTime: Instantiating.";
85 network_thread_.DetachFromThread();
86}
87
88void DelayBasedBwe::ComputeClusters(std::list<Cluster>* clusters) const {
89 Cluster current;
90 int64_t prev_send_time = -1;
91 int64_t prev_recv_time = -1;
92 int last_probe_cluster_id = -1;
93 for (std::list<Probe>::const_iterator it = probes_.begin();
94 it != probes_.end(); ++it) {
95 if (last_probe_cluster_id == -1)
96 last_probe_cluster_id = it->cluster_id;
97 if (prev_send_time >= 0) {
98 int send_delta_ms = it->send_time_ms - prev_send_time;
99 int recv_delta_ms = it->recv_time_ms - prev_recv_time;
100 if (send_delta_ms >= 1 && recv_delta_ms >= 1) {
101 ++current.num_above_min_delta;
102 }
103 if (it->cluster_id != last_probe_cluster_id) {
104 if (current.count >= kMinClusterSize)
105 AddCluster(clusters, &current);
106 current = Cluster();
107 }
108 current.send_mean_ms += send_delta_ms;
109 current.recv_mean_ms += recv_delta_ms;
110 current.mean_size += it->payload_size;
111 ++current.count;
112 last_probe_cluster_id = it->cluster_id;
113 }
114 prev_send_time = it->send_time_ms;
115 prev_recv_time = it->recv_time_ms;
116 }
117 if (current.count >= kMinClusterSize)
118 AddCluster(clusters, &current);
119}
120
121std::list<DelayBasedBwe::Cluster>::const_iterator DelayBasedBwe::FindBestProbe(
122 const std::list<Cluster>& clusters) const {
123 int highest_probe_bitrate_bps = 0;
124 std::list<Cluster>::const_iterator best_it = clusters.end();
125 for (std::list<Cluster>::const_iterator it = clusters.begin();
126 it != clusters.end(); ++it) {
127 if (it->send_mean_ms == 0 || it->recv_mean_ms == 0)
128 continue;
129 int send_bitrate_bps = it->mean_size * 8 * 1000 / it->send_mean_ms;
130 int recv_bitrate_bps = it->mean_size * 8 * 1000 / it->recv_mean_ms;
131 if (it->num_above_min_delta > it->count / 2 &&
132 (it->recv_mean_ms - it->send_mean_ms <= 2.0f &&
133 it->send_mean_ms - it->recv_mean_ms <= 5.0f)) {
134 int probe_bitrate_bps =
135 std::min(it->GetSendBitrateBps(), it->GetRecvBitrateBps());
136 if (probe_bitrate_bps > highest_probe_bitrate_bps) {
137 highest_probe_bitrate_bps = probe_bitrate_bps;
138 best_it = it;
139 }
140 } else {
141 LOG(LS_INFO) << "Probe failed, sent at " << send_bitrate_bps
142 << " bps, received at " << recv_bitrate_bps
143 << " bps. Mean send delta: " << it->send_mean_ms
144 << " ms, mean recv delta: " << it->recv_mean_ms
145 << " ms, num probes: " << it->count;
146 break;
147 }
148 }
149 return best_it;
150}
151
152DelayBasedBwe::ProbeResult DelayBasedBwe::ProcessClusters(int64_t now_ms) {
153 std::list<Cluster> clusters;
154 ComputeClusters(&clusters);
155 if (clusters.empty()) {
156 // If we reach the max number of probe packets and still have no clusters,
157 // we will remove the oldest one.
158 if (probes_.size() >= kMaxProbePackets)
159 probes_.pop_front();
160 return ProbeResult::kNoUpdate;
161 }
162
163 std::list<Cluster>::const_iterator best_it = FindBestProbe(clusters);
164 if (best_it != clusters.end()) {
165 int probe_bitrate_bps =
166 std::min(best_it->GetSendBitrateBps(), best_it->GetRecvBitrateBps());
167 // Make sure that a probe sent on a lower bitrate than our estimate can't
168 // reduce the estimate.
169 if (IsBitrateImproving(probe_bitrate_bps)) {
170 LOG(LS_INFO) << "Probe successful, sent at "
171 << best_it->GetSendBitrateBps() << " bps, received at "
172 << best_it->GetRecvBitrateBps()
173 << " bps. Mean send delta: " << best_it->send_mean_ms
174 << " ms, mean recv delta: " << best_it->recv_mean_ms
175 << " ms, num probes: " << best_it->count;
176 remote_rate_.SetEstimate(probe_bitrate_bps, now_ms);
177 return ProbeResult::kBitrateUpdated;
178 }
179 }
180
181 // Not probing and received non-probe packet, or finished with current set
182 // of probes.
183 if (clusters.size() >= kExpectedNumberOfProbes)
184 probes_.clear();
185 return ProbeResult::kNoUpdate;
186}
187
188bool DelayBasedBwe::IsBitrateImproving(int new_bitrate_bps) const {
189 bool initial_probe = !remote_rate_.ValidEstimate() && new_bitrate_bps > 0;
190 bool bitrate_above_estimate =
191 remote_rate_.ValidEstimate() &&
192 new_bitrate_bps > static_cast<int>(remote_rate_.LatestEstimate());
193 return initial_probe || bitrate_above_estimate;
194}
195
196void DelayBasedBwe::IncomingPacketFeedbackVector(
197 const std::vector<PacketInfo>& packet_feedback_vector) {
198 RTC_DCHECK(network_thread_.CalledOnValidThread());
199 for (const auto& packet_info : packet_feedback_vector) {
200 IncomingPacketInfo(packet_info.arrival_time_ms,
201 ConvertMsTo24Bits(packet_info.send_time_ms),
pbos2169d8b2016-06-20 11:53:02 -0700202 packet_info.payload_size, 0,
philipel863a8262016-06-17 09:21:34 -0700203 packet_info.probe_cluster_id);
204 }
205}
206
philipel863a8262016-06-17 09:21:34 -0700207void DelayBasedBwe::IncomingPacketInfo(int64_t arrival_time_ms,
208 uint32_t send_time_24bits,
209 size_t payload_size,
210 uint32_t ssrc,
philipel863a8262016-06-17 09:21:34 -0700211 int probe_cluster_id) {
212 assert(send_time_24bits < (1ul << 24));
213 // Shift up send time to use the full 32 bits that inter_arrival works with,
214 // so wrapping works properly.
215 uint32_t timestamp = send_time_24bits << kAbsSendTimeInterArrivalUpshift;
216 int64_t send_time_ms = static_cast<int64_t>(timestamp) * kTimestampToMs;
217
stefan5e12d362016-07-11 01:44:02 -0700218 int64_t now_ms = clock_->TimeInMilliseconds();
philipel863a8262016-06-17 09:21:34 -0700219 // TODO(holmer): SSRCs are only needed for REMB, should be broken out from
220 // here.
stefan5e12d362016-07-11 01:44:02 -0700221 incoming_bitrate_.Update(payload_size, arrival_time_ms);
philipel863a8262016-06-17 09:21:34 -0700222
223 if (first_packet_time_ms_ == -1)
stefan5e12d362016-07-11 01:44:02 -0700224 first_packet_time_ms_ = now_ms;
philipel863a8262016-06-17 09:21:34 -0700225
226 uint32_t ts_delta = 0;
227 int64_t t_delta = 0;
228 int size_delta = 0;
229
230 bool update_estimate = false;
231 uint32_t target_bitrate_bps = 0;
232 std::vector<uint32_t> ssrcs;
233 {
234 rtc::CritScope lock(&crit_);
235
236 TimeoutStreams(now_ms);
237 RTC_DCHECK(inter_arrival_.get());
238 RTC_DCHECK(estimator_.get());
239 ssrcs_[ssrc] = now_ms;
240
241 // For now only try to detect probes while we don't have a valid estimate,
242 // and make sure the packet was paced. We currently assume that only packets
243 // larger than 200 bytes are paced by the sender.
244 if (probe_cluster_id != PacketInfo::kNotAProbe &&
245 payload_size > PacedSender::kMinProbePacketSize &&
246 (!remote_rate_.ValidEstimate() ||
247 now_ms - first_packet_time_ms_ < kInitialProbingIntervalMs)) {
248 // TODO(holmer): Use a map instead to get correct order?
249 if (total_probes_received_ < kMaxProbePackets) {
250 int send_delta_ms = -1;
251 int recv_delta_ms = -1;
252 if (!probes_.empty()) {
253 send_delta_ms = send_time_ms - probes_.back().send_time_ms;
254 recv_delta_ms = arrival_time_ms - probes_.back().recv_time_ms;
255 }
256 LOG(LS_INFO) << "Probe packet received: send time=" << send_time_ms
257 << " ms, recv time=" << arrival_time_ms
258 << " ms, send delta=" << send_delta_ms
259 << " ms, recv delta=" << recv_delta_ms << " ms.";
260 }
261 probes_.push_back(
262 Probe(send_time_ms, arrival_time_ms, payload_size, probe_cluster_id));
263 ++total_probes_received_;
264 // Make sure that a probe which updated the bitrate immediately has an
265 // effect by calling the OnReceiveBitrateChanged callback.
266 if (ProcessClusters(now_ms) == ProbeResult::kBitrateUpdated)
267 update_estimate = true;
268 }
stefan5e12d362016-07-11 01:44:02 -0700269 if (inter_arrival_->ComputeDeltas(timestamp, arrival_time_ms, now_ms,
270 payload_size, &ts_delta, &t_delta,
271 &size_delta)) {
philipel863a8262016-06-17 09:21:34 -0700272 double ts_delta_ms = (1000.0 * ts_delta) / (1 << kInterArrivalShift);
273 estimator_->Update(t_delta, ts_delta_ms, size_delta, detector_.State());
274 detector_.Detect(estimator_->offset(), ts_delta_ms,
275 estimator_->num_of_deltas(), arrival_time_ms);
276 }
277
278 if (!update_estimate) {
279 // Check if it's time for a periodic update or if we should update because
280 // of an over-use.
281 if (last_update_ms_ == -1 ||
282 now_ms - last_update_ms_ > remote_rate_.GetFeedbackInterval()) {
283 update_estimate = true;
284 } else if (detector_.State() == kBwOverusing) {
stefan5e12d362016-07-11 01:44:02 -0700285 rtc::Optional<uint32_t> incoming_rate =
286 incoming_bitrate_.Rate(arrival_time_ms);
philipel863a8262016-06-17 09:21:34 -0700287 if (incoming_rate &&
288 remote_rate_.TimeToReduceFurther(now_ms, *incoming_rate)) {
289 update_estimate = true;
290 }
291 }
292 }
293
294 if (update_estimate) {
295 // The first overuse should immediately trigger a new estimate.
296 // We also have to update the estimate immediately if we are overusing
297 // and the target bitrate is too high compared to what we are receiving.
298 const RateControlInput input(detector_.State(),
stefan5e12d362016-07-11 01:44:02 -0700299 incoming_bitrate_.Rate(arrival_time_ms),
philipel863a8262016-06-17 09:21:34 -0700300 estimator_->var_noise());
301 remote_rate_.Update(&input, now_ms);
302 target_bitrate_bps = remote_rate_.UpdateBandwidthEstimate(now_ms);
303 update_estimate = remote_rate_.ValidEstimate();
304 ssrcs = Keys(ssrcs_);
305 }
306 }
307 if (update_estimate) {
308 last_update_ms_ = now_ms;
309 observer_->OnReceiveBitrateChanged(ssrcs, target_bitrate_bps);
310 }
311}
312
313void DelayBasedBwe::Process() {}
314
315int64_t DelayBasedBwe::TimeUntilNextProcess() {
316 const int64_t kDisabledModuleTime = 1000;
317 return kDisabledModuleTime;
318}
319
320void DelayBasedBwe::TimeoutStreams(int64_t now_ms) {
321 for (Ssrcs::iterator it = ssrcs_.begin(); it != ssrcs_.end();) {
322 if ((now_ms - it->second) > kStreamTimeOutMs) {
323 ssrcs_.erase(it++);
324 } else {
325 ++it;
326 }
327 }
328 if (ssrcs_.empty()) {
329 // We can't update the estimate if we don't have any active streams.
330 inter_arrival_.reset(
331 new InterArrival((kTimestampGroupLengthMs << kInterArrivalShift) / 1000,
332 kTimestampToMs, true));
333 estimator_.reset(new OveruseEstimator(OverUseDetectorOptions()));
334 // We deliberately don't reset the first_packet_time_ms_ here for now since
335 // we only probe for bandwidth in the beginning of a call right now.
336 }
337}
338
339void DelayBasedBwe::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) {
340 rtc::CritScope lock(&crit_);
341 remote_rate_.SetRtt(avg_rtt_ms);
342}
343
344void DelayBasedBwe::RemoveStream(uint32_t ssrc) {
345 rtc::CritScope lock(&crit_);
346 ssrcs_.erase(ssrc);
347}
348
349bool DelayBasedBwe::LatestEstimate(std::vector<uint32_t>* ssrcs,
350 uint32_t* bitrate_bps) const {
351 // Currently accessed from both the process thread (see
352 // ModuleRtpRtcpImpl::Process()) and the configuration thread (see
353 // Call::GetStats()). Should in the future only be accessed from a single
354 // thread.
355 RTC_DCHECK(ssrcs);
356 RTC_DCHECK(bitrate_bps);
357 rtc::CritScope lock(&crit_);
358 if (!remote_rate_.ValidEstimate()) {
359 return false;
360 }
361 *ssrcs = Keys(ssrcs_);
362 if (ssrcs_.empty()) {
363 *bitrate_bps = 0;
364 } else {
365 *bitrate_bps = remote_rate_.LatestEstimate();
366 }
367 return true;
368}
369
370void DelayBasedBwe::SetMinBitrate(int min_bitrate_bps) {
371 // Called from both the configuration thread and the network thread. Shouldn't
372 // be called from the network thread in the future.
373 rtc::CritScope lock(&crit_);
374 remote_rate_.SetMinBitrate(min_bitrate_bps);
375}
376} // namespace webrtc