media/mtransport/simpletokenbucket.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/media/mtransport/simpletokenbucket.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,62 @@
     1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
     1.5 +/* vim: set ts=2 et sw=2 tw=80: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     1.8 + * You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +/* Original author: bcampen@mozilla.com */
    1.11 +
    1.12 +#include "simpletokenbucket.h"
    1.13 +
    1.14 +#include <stdint.h>
    1.15 +
    1.16 +#include "prinrval.h"
    1.17 +
    1.18 +namespace mozilla {
    1.19 +
    1.20 +SimpleTokenBucket::SimpleTokenBucket(size_t bucket_size,
    1.21 +                                     size_t tokens_per_second) :
    1.22 +  max_tokens_(bucket_size),
    1.23 +  num_tokens_(bucket_size),
    1.24 +  tokens_per_second_(tokens_per_second),
    1.25 +  last_time_tokens_added_(PR_IntervalNow()) {
    1.26 +}
    1.27 +
    1.28 +size_t SimpleTokenBucket::getTokens(size_t num_requested_tokens) {
    1.29 +  // Only fill if there isn't enough to satisfy the request.
    1.30 +  // If we get tokens so seldomly that we are able to roll the timer all
    1.31 +  // the way around its range, then we lose that entire range of time
    1.32 +  // for token accumulation. Probably not the end of the world.
    1.33 +  if (num_requested_tokens > num_tokens_) {
    1.34 +    PRIntervalTime now = PR_IntervalNow();
    1.35 +
    1.36 +    // If we roll over the max, since everything in this calculation is the same
    1.37 +    // unsigned type, this will still yield the elapsed time (unless we've
    1.38 +    // wrapped more than once).
    1.39 +    PRIntervalTime elapsed_ticks = now - last_time_tokens_added_;
    1.40 +
    1.41 +    uint32_t elapsed_milli_sec = PR_IntervalToMilliseconds(elapsed_ticks);
    1.42 +    size_t tokens_to_add = (elapsed_milli_sec * tokens_per_second_)/1000;
    1.43 +
    1.44 +    // Only update our timestamp if we added some tokens
    1.45 +    // TODO:(bcampen@mozilla.com) Should we attempt to "save" leftover time?
    1.46 +    if (tokens_to_add) {
    1.47 +      num_tokens_ += tokens_to_add;
    1.48 +      if (num_tokens_ > max_tokens_) {
    1.49 +        num_tokens_ = max_tokens_;
    1.50 +      }
    1.51 +
    1.52 +      last_time_tokens_added_ = now;
    1.53 +    }
    1.54 +
    1.55 +    if (num_requested_tokens > num_tokens_) {
    1.56 +      return num_tokens_;
    1.57 +    }
    1.58 +  }
    1.59 +
    1.60 +  num_tokens_ -= num_requested_tokens;
    1.61 +  return num_requested_tokens;
    1.62 +}
    1.63 +
    1.64 +} // namespace mozilla
    1.65 +

mercurial