• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2015 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 
12 #include "call/bitrate_allocator.h"
13 
14 #include <algorithm>
15 #include <cmath>
16 #include <memory>
17 #include <utility>
18 
19 #include "absl/algorithm/container.h"
20 #include "api/units/data_rate.h"
21 #include "api/units/time_delta.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/logging.h"
24 #include "rtc_base/numerics/safe_minmax.h"
25 #include "system_wrappers/include/clock.h"
26 #include "system_wrappers/include/field_trial.h"
27 #include "system_wrappers/include/metrics.h"
28 
29 namespace webrtc {
30 
31 namespace {
32 using bitrate_allocator_impl::AllocatableTrack;
33 
34 // Allow packets to be transmitted in up to 2 times max video bitrate if the
35 // bandwidth estimate allows it.
36 const uint8_t kTransmissionMaxBitrateMultiplier = 2;
37 const int kDefaultBitrateBps = 300000;
38 
39 // Require a bitrate increase of max(10%, 20kbps) to resume paused streams.
40 const double kToggleFactor = 0.1;
41 const uint32_t kMinToggleBitrateBps = 20000;
42 
43 const int64_t kBweLogIntervalMs = 5000;
44 
MediaRatio(uint32_t allocated_bitrate,uint32_t protection_bitrate)45 double MediaRatio(uint32_t allocated_bitrate, uint32_t protection_bitrate) {
46   RTC_DCHECK_GT(allocated_bitrate, 0);
47   if (protection_bitrate == 0)
48     return 1.0;
49 
50   uint32_t media_bitrate = allocated_bitrate - protection_bitrate;
51   return media_bitrate / static_cast<double>(allocated_bitrate);
52 }
53 
EnoughBitrateForAllObservers(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate,uint32_t sum_min_bitrates)54 bool EnoughBitrateForAllObservers(
55     const std::vector<AllocatableTrack>& allocatable_tracks,
56     uint32_t bitrate,
57     uint32_t sum_min_bitrates) {
58   if (bitrate < sum_min_bitrates)
59     return false;
60 
61   uint32_t extra_bitrate_per_observer =
62       (bitrate - sum_min_bitrates) /
63       static_cast<uint32_t>(allocatable_tracks.size());
64   for (const auto& observer_config : allocatable_tracks) {
65     if (observer_config.config.min_bitrate_bps + extra_bitrate_per_observer <
66         observer_config.MinBitrateWithHysteresis()) {
67       return false;
68     }
69   }
70   return true;
71 }
72 
73 // Splits |bitrate| evenly to observers already in |allocation|.
74 // |include_zero_allocations| decides if zero allocations should be part of
75 // the distribution or not. The allowed max bitrate is |max_multiplier| x
76 // observer max bitrate.
DistributeBitrateEvenly(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate,bool include_zero_allocations,int max_multiplier,std::map<BitrateAllocatorObserver *,int> * allocation)77 void DistributeBitrateEvenly(
78     const std::vector<AllocatableTrack>& allocatable_tracks,
79     uint32_t bitrate,
80     bool include_zero_allocations,
81     int max_multiplier,
82     std::map<BitrateAllocatorObserver*, int>* allocation) {
83   RTC_DCHECK_EQ(allocation->size(), allocatable_tracks.size());
84 
85   std::multimap<uint32_t, const AllocatableTrack*> list_max_bitrates;
86   for (const auto& observer_config : allocatable_tracks) {
87     if (include_zero_allocations ||
88         allocation->at(observer_config.observer) != 0) {
89       list_max_bitrates.insert(
90           {observer_config.config.max_bitrate_bps, &observer_config});
91     }
92   }
93   auto it = list_max_bitrates.begin();
94   while (it != list_max_bitrates.end()) {
95     RTC_DCHECK_GT(bitrate, 0);
96     uint32_t extra_allocation =
97         bitrate / static_cast<uint32_t>(list_max_bitrates.size());
98     uint32_t total_allocation =
99         extra_allocation + allocation->at(it->second->observer);
100     bitrate -= extra_allocation;
101     if (total_allocation > max_multiplier * it->first) {
102       // There is more than we can fit for this observer, carry over to the
103       // remaining observers.
104       bitrate += total_allocation - max_multiplier * it->first;
105       total_allocation = max_multiplier * it->first;
106     }
107     // Finally, update the allocation for this observer.
108     allocation->at(it->second->observer) = total_allocation;
109     it = list_max_bitrates.erase(it);
110   }
111 }
112 
113 // From the available |bitrate|, each observer will be allocated a
114 // proportional amount based upon its bitrate priority. If that amount is
115 // more than the observer's capacity, it will be allocated its capacity, and
116 // the excess bitrate is still allocated proportionally to other observers.
117 // Allocating the proportional amount means an observer with twice the
118 // bitrate_priority of another will be allocated twice the bitrate.
DistributeBitrateRelatively(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t remaining_bitrate,const std::map<BitrateAllocatorObserver *,int> & observers_capacities,std::map<BitrateAllocatorObserver *,int> * allocation)119 void DistributeBitrateRelatively(
120     const std::vector<AllocatableTrack>& allocatable_tracks,
121     uint32_t remaining_bitrate,
122     const std::map<BitrateAllocatorObserver*, int>& observers_capacities,
123     std::map<BitrateAllocatorObserver*, int>* allocation) {
124   RTC_DCHECK_EQ(allocation->size(), allocatable_tracks.size());
125   RTC_DCHECK_EQ(observers_capacities.size(), allocatable_tracks.size());
126 
127   struct PriorityRateObserverConfig {
128     BitrateAllocatorObserver* allocation_key;
129     // The amount of bitrate bps that can be allocated to this observer.
130     int capacity_bps;
131     double bitrate_priority;
132   };
133 
134   double bitrate_priority_sum = 0;
135   std::vector<PriorityRateObserverConfig> priority_rate_observers;
136   for (const auto& observer_config : allocatable_tracks) {
137     priority_rate_observers.push_back(PriorityRateObserverConfig{
138         observer_config.observer,
139         observers_capacities.at(observer_config.observer),
140         observer_config.config.bitrate_priority});
141     bitrate_priority_sum += observer_config.config.bitrate_priority;
142   }
143 
144   // Iterate in the order observers can be allocated their full capacity.
145 
146   // We want to sort by which observers will be allocated their full capacity
147   // first. By dividing each observer's capacity by its bitrate priority we
148   // are "normalizing" the capacity of an observer by the rate it will be
149   // filled. This is because the amount allocated is based upon bitrate
150   // priority. We allocate twice as much bitrate to an observer with twice the
151   // bitrate priority of another.
152   absl::c_sort(priority_rate_observers, [](const auto& a, const auto& b) {
153     return a.capacity_bps / a.bitrate_priority <
154            b.capacity_bps / b.bitrate_priority;
155   });
156   size_t i;
157   for (i = 0; i < priority_rate_observers.size(); ++i) {
158     const auto& priority_rate_observer = priority_rate_observers[i];
159     // We allocate the full capacity to an observer only if its relative
160     // portion from the remaining bitrate is sufficient to allocate its full
161     // capacity. This means we aren't greedily allocating the full capacity, but
162     // that it is only done when there is also enough bitrate to allocate the
163     // proportional amounts to all other observers.
164     double observer_share =
165         priority_rate_observer.bitrate_priority / bitrate_priority_sum;
166     double allocation_bps = observer_share * remaining_bitrate;
167     bool enough_bitrate = allocation_bps >= priority_rate_observer.capacity_bps;
168     if (!enough_bitrate)
169       break;
170     allocation->at(priority_rate_observer.allocation_key) +=
171         priority_rate_observer.capacity_bps;
172     remaining_bitrate -= priority_rate_observer.capacity_bps;
173     bitrate_priority_sum -= priority_rate_observer.bitrate_priority;
174   }
175 
176   // From the remaining bitrate, allocate the proportional amounts to the
177   // observers that aren't allocated their max capacity.
178   for (; i < priority_rate_observers.size(); ++i) {
179     const auto& priority_rate_observer = priority_rate_observers[i];
180     double fraction_allocated =
181         priority_rate_observer.bitrate_priority / bitrate_priority_sum;
182     allocation->at(priority_rate_observer.allocation_key) +=
183         fraction_allocated * remaining_bitrate;
184   }
185 }
186 
187 // Allocates bitrate to observers when there isn't enough to allocate the
188 // minimum to all observers.
LowRateAllocation(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate)189 std::map<BitrateAllocatorObserver*, int> LowRateAllocation(
190     const std::vector<AllocatableTrack>& allocatable_tracks,
191     uint32_t bitrate) {
192   std::map<BitrateAllocatorObserver*, int> allocation;
193   // Start by allocating bitrate to observers enforcing a min bitrate, hence
194   // remaining_bitrate might turn negative.
195   int64_t remaining_bitrate = bitrate;
196   for (const auto& observer_config : allocatable_tracks) {
197     int32_t allocated_bitrate = 0;
198     if (observer_config.config.enforce_min_bitrate)
199       allocated_bitrate = observer_config.config.min_bitrate_bps;
200 
201     allocation[observer_config.observer] = allocated_bitrate;
202     remaining_bitrate -= allocated_bitrate;
203   }
204 
205   // Allocate bitrate to all previously active streams.
206   if (remaining_bitrate > 0) {
207     for (const auto& observer_config : allocatable_tracks) {
208       if (observer_config.config.enforce_min_bitrate ||
209           observer_config.LastAllocatedBitrate() == 0)
210         continue;
211 
212       uint32_t required_bitrate = observer_config.MinBitrateWithHysteresis();
213       if (remaining_bitrate >= required_bitrate) {
214         allocation[observer_config.observer] = required_bitrate;
215         remaining_bitrate -= required_bitrate;
216       }
217     }
218   }
219 
220   // Allocate bitrate to previously paused streams.
221   if (remaining_bitrate > 0) {
222     for (const auto& observer_config : allocatable_tracks) {
223       if (observer_config.LastAllocatedBitrate() != 0)
224         continue;
225 
226       // Add a hysteresis to avoid toggling.
227       uint32_t required_bitrate = observer_config.MinBitrateWithHysteresis();
228       if (remaining_bitrate >= required_bitrate) {
229         allocation[observer_config.observer] = required_bitrate;
230         remaining_bitrate -= required_bitrate;
231       }
232     }
233   }
234 
235   // Split a possible remainder evenly on all streams with an allocation.
236   if (remaining_bitrate > 0)
237     DistributeBitrateEvenly(allocatable_tracks, remaining_bitrate, false, 1,
238                             &allocation);
239 
240   RTC_DCHECK_EQ(allocation.size(), allocatable_tracks.size());
241   return allocation;
242 }
243 
244 // Allocates bitrate to all observers when the available bandwidth is enough
245 // to allocate the minimum to all observers but not enough to allocate the
246 // max bitrate of each observer.
247 
248 // Allocates the bitrate based on the bitrate priority of each observer. This
249 // bitrate priority defines the priority for bitrate to be allocated to that
250 // observer in relation to other observers. For example with two observers, if
251 // observer 1 had a bitrate_priority = 1.0, and observer 2 has a
252 // bitrate_priority = 2.0, the expected behavior is that observer 2 will be
253 // allocated twice the bitrate as observer 1 above the each observer's
254 // min_bitrate_bps values, until one of the observers hits its max_bitrate_bps.
NormalRateAllocation(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate,uint32_t sum_min_bitrates)255 std::map<BitrateAllocatorObserver*, int> NormalRateAllocation(
256     const std::vector<AllocatableTrack>& allocatable_tracks,
257     uint32_t bitrate,
258     uint32_t sum_min_bitrates) {
259   std::map<BitrateAllocatorObserver*, int> allocation;
260   std::map<BitrateAllocatorObserver*, int> observers_capacities;
261   for (const auto& observer_config : allocatable_tracks) {
262     allocation[observer_config.observer] =
263         observer_config.config.min_bitrate_bps;
264     observers_capacities[observer_config.observer] =
265         observer_config.config.max_bitrate_bps -
266         observer_config.config.min_bitrate_bps;
267   }
268 
269   bitrate -= sum_min_bitrates;
270 
271   // TODO(srte): Implement fair sharing between prioritized streams, currently
272   // they are treated on a first come first serve basis.
273   for (const auto& observer_config : allocatable_tracks) {
274     int64_t priority_margin = observer_config.config.priority_bitrate_bps -
275                               allocation[observer_config.observer];
276     if (priority_margin > 0 && bitrate > 0) {
277       int64_t extra_bitrate = std::min<int64_t>(priority_margin, bitrate);
278       allocation[observer_config.observer] +=
279           rtc::dchecked_cast<int>(extra_bitrate);
280       observers_capacities[observer_config.observer] -= extra_bitrate;
281       bitrate -= extra_bitrate;
282     }
283   }
284 
285   // From the remaining bitrate, allocate a proportional amount to each observer
286   // above the min bitrate already allocated.
287   if (bitrate > 0)
288     DistributeBitrateRelatively(allocatable_tracks, bitrate,
289                                 observers_capacities, &allocation);
290 
291   return allocation;
292 }
293 
294 // Allocates bitrate to observers when there is enough available bandwidth
295 // for all observers to be allocated their max bitrate.
MaxRateAllocation(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate,uint32_t sum_max_bitrates)296 std::map<BitrateAllocatorObserver*, int> MaxRateAllocation(
297     const std::vector<AllocatableTrack>& allocatable_tracks,
298     uint32_t bitrate,
299     uint32_t sum_max_bitrates) {
300   std::map<BitrateAllocatorObserver*, int> allocation;
301 
302   for (const auto& observer_config : allocatable_tracks) {
303     allocation[observer_config.observer] =
304         observer_config.config.max_bitrate_bps;
305     bitrate -= observer_config.config.max_bitrate_bps;
306   }
307   DistributeBitrateEvenly(allocatable_tracks, bitrate, true,
308                           kTransmissionMaxBitrateMultiplier, &allocation);
309   return allocation;
310 }
311 
312 // Allocates zero bitrate to all observers.
ZeroRateAllocation(const std::vector<AllocatableTrack> & allocatable_tracks)313 std::map<BitrateAllocatorObserver*, int> ZeroRateAllocation(
314     const std::vector<AllocatableTrack>& allocatable_tracks) {
315   std::map<BitrateAllocatorObserver*, int> allocation;
316   for (const auto& observer_config : allocatable_tracks)
317     allocation[observer_config.observer] = 0;
318   return allocation;
319 }
320 
AllocateBitrates(const std::vector<AllocatableTrack> & allocatable_tracks,uint32_t bitrate)321 std::map<BitrateAllocatorObserver*, int> AllocateBitrates(
322     const std::vector<AllocatableTrack>& allocatable_tracks,
323     uint32_t bitrate) {
324   if (allocatable_tracks.empty())
325     return std::map<BitrateAllocatorObserver*, int>();
326 
327   if (bitrate == 0)
328     return ZeroRateAllocation(allocatable_tracks);
329 
330   uint32_t sum_min_bitrates = 0;
331   uint32_t sum_max_bitrates = 0;
332   for (const auto& observer_config : allocatable_tracks) {
333     sum_min_bitrates += observer_config.config.min_bitrate_bps;
334     sum_max_bitrates += observer_config.config.max_bitrate_bps;
335   }
336 
337   // Not enough for all observers to get an allocation, allocate according to:
338   // enforced min bitrate -> allocated bitrate previous round -> restart paused
339   // streams.
340   if (!EnoughBitrateForAllObservers(allocatable_tracks, bitrate,
341                                     sum_min_bitrates))
342     return LowRateAllocation(allocatable_tracks, bitrate);
343 
344   // All observers will get their min bitrate plus a share of the rest. This
345   // share is allocated to each observer based on its bitrate_priority.
346   if (bitrate <= sum_max_bitrates)
347     return NormalRateAllocation(allocatable_tracks, bitrate, sum_min_bitrates);
348 
349   // All observers will get up to transmission_max_bitrate_multiplier_ x max.
350   return MaxRateAllocation(allocatable_tracks, bitrate, sum_max_bitrates);
351 }
352 
353 }  // namespace
354 
BitrateAllocator(LimitObserver * limit_observer)355 BitrateAllocator::BitrateAllocator(LimitObserver* limit_observer)
356     : limit_observer_(limit_observer),
357       last_target_bps_(0),
358       last_stable_target_bps_(0),
359       last_non_zero_bitrate_bps_(kDefaultBitrateBps),
360       last_fraction_loss_(0),
361       last_rtt_(0),
362       last_bwe_period_ms_(1000),
363       num_pause_events_(0),
364       last_bwe_log_time_(0) {
365   sequenced_checker_.Detach();
366 }
367 
~BitrateAllocator()368 BitrateAllocator::~BitrateAllocator() {
369   RTC_HISTOGRAM_COUNTS_100("WebRTC.Call.NumberOfPauseEvents",
370                            num_pause_events_);
371 }
372 
UpdateStartRate(uint32_t start_rate_bps)373 void BitrateAllocator::UpdateStartRate(uint32_t start_rate_bps) {
374   RTC_DCHECK_RUN_ON(&sequenced_checker_);
375   last_non_zero_bitrate_bps_ = start_rate_bps;
376 }
377 
OnNetworkEstimateChanged(TargetTransferRate msg)378 void BitrateAllocator::OnNetworkEstimateChanged(TargetTransferRate msg) {
379   RTC_DCHECK_RUN_ON(&sequenced_checker_);
380   last_target_bps_ = msg.target_rate.bps();
381   last_stable_target_bps_ = msg.stable_target_rate.bps();
382   last_non_zero_bitrate_bps_ =
383       last_target_bps_ > 0 ? last_target_bps_ : last_non_zero_bitrate_bps_;
384 
385   int loss_ratio_255 = msg.network_estimate.loss_rate_ratio * 255;
386   last_fraction_loss_ =
387       rtc::dchecked_cast<uint8_t>(rtc::SafeClamp(loss_ratio_255, 0, 255));
388   last_rtt_ = msg.network_estimate.round_trip_time.ms();
389   last_bwe_period_ms_ = msg.network_estimate.bwe_period.ms();
390 
391   // Periodically log the incoming BWE.
392   int64_t now = msg.at_time.ms();
393   if (now > last_bwe_log_time_ + kBweLogIntervalMs) {
394     RTC_LOG(LS_INFO) << "Current BWE " << last_target_bps_;
395     last_bwe_log_time_ = now;
396   }
397 
398   auto allocation = AllocateBitrates(allocatable_tracks_, last_target_bps_);
399   auto stable_bitrate_allocation =
400       AllocateBitrates(allocatable_tracks_, last_stable_target_bps_);
401 
402   for (auto& config : allocatable_tracks_) {
403     uint32_t allocated_bitrate = allocation[config.observer];
404     uint32_t allocated_stable_target_rate =
405         stable_bitrate_allocation[config.observer];
406     BitrateAllocationUpdate update;
407     update.target_bitrate = DataRate::BitsPerSec(allocated_bitrate);
408     update.stable_target_bitrate =
409         DataRate::BitsPerSec(allocated_stable_target_rate);
410     update.packet_loss_ratio = last_fraction_loss_ / 256.0;
411     update.round_trip_time = TimeDelta::Millis(last_rtt_);
412     update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_);
413     update.cwnd_reduce_ratio = msg.cwnd_reduce_ratio;
414     uint32_t protection_bitrate = config.observer->OnBitrateUpdated(update);
415 
416     if (allocated_bitrate == 0 && config.allocated_bitrate_bps > 0) {
417       if (last_target_bps_ > 0)
418         ++num_pause_events_;
419       // The protection bitrate is an estimate based on the ratio between media
420       // and protection used before this observer was muted.
421       uint32_t predicted_protection_bps =
422           (1.0 - config.media_ratio) * config.config.min_bitrate_bps;
423       RTC_LOG(LS_INFO) << "Pausing observer " << config.observer
424                        << " with configured min bitrate "
425                        << config.config.min_bitrate_bps
426                        << " and current estimate of " << last_target_bps_
427                        << " and protection bitrate "
428                        << predicted_protection_bps;
429     } else if (allocated_bitrate > 0 && config.allocated_bitrate_bps == 0) {
430       if (last_target_bps_ > 0)
431         ++num_pause_events_;
432       RTC_LOG(LS_INFO) << "Resuming observer " << config.observer
433                        << ", configured min bitrate "
434                        << config.config.min_bitrate_bps
435                        << ", current allocation " << allocated_bitrate
436                        << " and protection bitrate " << protection_bitrate;
437     }
438 
439     // Only update the media ratio if the observer got an allocation.
440     if (allocated_bitrate > 0)
441       config.media_ratio = MediaRatio(allocated_bitrate, protection_bitrate);
442     config.allocated_bitrate_bps = allocated_bitrate;
443   }
444   UpdateAllocationLimits();
445 }
446 
AddObserver(BitrateAllocatorObserver * observer,MediaStreamAllocationConfig config)447 void BitrateAllocator::AddObserver(BitrateAllocatorObserver* observer,
448                                    MediaStreamAllocationConfig config) {
449   RTC_DCHECK_RUN_ON(&sequenced_checker_);
450   RTC_DCHECK_GT(config.bitrate_priority, 0);
451   RTC_DCHECK(std::isnormal(config.bitrate_priority));
452   auto it = absl::c_find_if(
453       allocatable_tracks_,
454       [observer](const auto& config) { return config.observer == observer; });
455   // Update settings if the observer already exists, create a new one otherwise.
456   if (it != allocatable_tracks_.end()) {
457     it->config = config;
458   } else {
459     allocatable_tracks_.push_back(AllocatableTrack(observer, config));
460   }
461 
462   if (last_target_bps_ > 0) {
463     // Calculate a new allocation and update all observers.
464 
465     auto allocation = AllocateBitrates(allocatable_tracks_, last_target_bps_);
466     auto stable_bitrate_allocation =
467         AllocateBitrates(allocatable_tracks_, last_stable_target_bps_);
468     for (auto& config : allocatable_tracks_) {
469       uint32_t allocated_bitrate = allocation[config.observer];
470       uint32_t allocated_stable_bitrate =
471           stable_bitrate_allocation[config.observer];
472       BitrateAllocationUpdate update;
473       update.target_bitrate = DataRate::BitsPerSec(allocated_bitrate);
474       update.stable_target_bitrate =
475           DataRate::BitsPerSec(allocated_stable_bitrate);
476       update.packet_loss_ratio = last_fraction_loss_ / 256.0;
477       update.round_trip_time = TimeDelta::Millis(last_rtt_);
478       update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_);
479       uint32_t protection_bitrate = config.observer->OnBitrateUpdated(update);
480       config.allocated_bitrate_bps = allocated_bitrate;
481       if (allocated_bitrate > 0)
482         config.media_ratio = MediaRatio(allocated_bitrate, protection_bitrate);
483     }
484   } else {
485     // Currently, an encoder is not allowed to produce frames.
486     // But we still have to return the initial config bitrate + let the
487     // observer know that it can not produce frames.
488 
489     BitrateAllocationUpdate update;
490     update.target_bitrate = DataRate::Zero();
491     update.stable_target_bitrate = DataRate::Zero();
492     update.packet_loss_ratio = last_fraction_loss_ / 256.0;
493     update.round_trip_time = TimeDelta::Millis(last_rtt_);
494     update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_);
495     observer->OnBitrateUpdated(update);
496   }
497   UpdateAllocationLimits();
498 }
499 
UpdateAllocationLimits()500 void BitrateAllocator::UpdateAllocationLimits() {
501   BitrateAllocationLimits limits;
502   for (const auto& config : allocatable_tracks_) {
503     uint32_t stream_padding = config.config.pad_up_bitrate_bps;
504     if (config.config.enforce_min_bitrate) {
505       limits.min_allocatable_rate +=
506           DataRate::BitsPerSec(config.config.min_bitrate_bps);
507     } else if (config.allocated_bitrate_bps == 0) {
508       stream_padding =
509           std::max(config.MinBitrateWithHysteresis(), stream_padding);
510     }
511     limits.max_padding_rate += DataRate::BitsPerSec(stream_padding);
512     limits.max_allocatable_rate +=
513         DataRate::BitsPerSec(config.config.max_bitrate_bps);
514   }
515 
516   if (limits.min_allocatable_rate == current_limits_.min_allocatable_rate &&
517       limits.max_allocatable_rate == current_limits_.max_allocatable_rate &&
518       limits.max_padding_rate == current_limits_.max_padding_rate) {
519     return;
520   }
521   current_limits_ = limits;
522 
523   RTC_LOG(LS_INFO) << "UpdateAllocationLimits : total_requested_min_bitrate: "
524                    << ToString(limits.min_allocatable_rate)
525                    << ", total_requested_padding_bitrate: "
526                    << ToString(limits.max_padding_rate)
527                    << ", total_requested_max_bitrate: "
528                    << ToString(limits.max_allocatable_rate);
529 
530   limit_observer_->OnAllocationLimitsChanged(limits);
531 }
532 
RemoveObserver(BitrateAllocatorObserver * observer)533 void BitrateAllocator::RemoveObserver(BitrateAllocatorObserver* observer) {
534   RTC_DCHECK_RUN_ON(&sequenced_checker_);
535   for (auto it = allocatable_tracks_.begin(); it != allocatable_tracks_.end();
536        ++it) {
537     if (it->observer == observer) {
538       allocatable_tracks_.erase(it);
539       break;
540     }
541   }
542 
543   UpdateAllocationLimits();
544 }
545 
GetStartBitrate(BitrateAllocatorObserver * observer) const546 int BitrateAllocator::GetStartBitrate(
547     BitrateAllocatorObserver* observer) const {
548   RTC_DCHECK_RUN_ON(&sequenced_checker_);
549   auto it = absl::c_find_if(
550       allocatable_tracks_,
551       [observer](const auto& config) { return config.observer == observer; });
552   if (it == allocatable_tracks_.end()) {
553     // This observer hasn't been added yet, just give it its fair share.
554     return last_non_zero_bitrate_bps_ /
555            static_cast<int>((allocatable_tracks_.size() + 1));
556   } else if (it->allocated_bitrate_bps == -1) {
557     // This observer hasn't received an allocation yet, so do the same.
558     return last_non_zero_bitrate_bps_ /
559            static_cast<int>(allocatable_tracks_.size());
560   } else {
561     // This observer already has an allocation.
562     return it->allocated_bitrate_bps;
563   }
564 }
565 
LastAllocatedBitrate() const566 uint32_t bitrate_allocator_impl::AllocatableTrack::LastAllocatedBitrate()
567     const {
568   // Return the configured minimum bitrate for newly added observers, to avoid
569   // requiring an extra high bitrate for the observer to get an allocated
570   // bitrate.
571   return allocated_bitrate_bps == -1 ? config.min_bitrate_bps
572                                      : allocated_bitrate_bps;
573 }
574 
MinBitrateWithHysteresis() const575 uint32_t bitrate_allocator_impl::AllocatableTrack::MinBitrateWithHysteresis()
576     const {
577   uint32_t min_bitrate = config.min_bitrate_bps;
578   if (LastAllocatedBitrate() == 0) {
579     min_bitrate += std::max(static_cast<uint32_t>(kToggleFactor * min_bitrate),
580                             kMinToggleBitrateBps);
581   }
582   // Account for protection bitrate used by this observer in the previous
583   // allocation.
584   // Note: the ratio will only be updated when the stream is active, meaning a
585   // paused stream won't get any ratio updates. This might lead to waiting a bit
586   // longer than necessary if the network condition improves, but this is to
587   // avoid too much toggling.
588   if (media_ratio > 0.0 && media_ratio < 1.0)
589     min_bitrate += min_bitrate * (1.0 - media_ratio);
590 
591   return min_bitrate;
592 }
593 
594 }  // namespace webrtc
595