smooth_event_sampler.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "media/capture/content/smooth_event_sampler.h"
  5. #include <stdint.h>
  6. #include <algorithm>
  7. #include "base/trace_event/trace_event.h"
  8. namespace media {
  9. SmoothEventSampler::SmoothEventSampler(base::TimeDelta min_capture_period)
  10. : token_bucket_(base::TimeDelta::Max()) {
  11. SetMinCapturePeriod(min_capture_period);
  12. }
  13. void SmoothEventSampler::SetMinCapturePeriod(base::TimeDelta period) {
  14. DCHECK_GT(period, base::TimeDelta());
  15. if (period == min_capture_period_)
  16. return;
  17. min_capture_period_ = period;
  18. token_bucket_capacity_ = period + period / 2;
  19. token_bucket_ = std::min(token_bucket_capacity_, token_bucket_);
  20. }
  21. void SmoothEventSampler::ConsiderPresentationEvent(base::TimeTicks event_time) {
  22. DCHECK(!event_time.is_null());
  23. // Add tokens to the bucket based on advancement in time. Then, re-bound the
  24. // number of tokens in the bucket. Overflow occurs when there is too much
  25. // time between events (a common case), or when RecordSample() is not being
  26. // called often enough (a bug). On the other hand, if RecordSample() is being
  27. // called too often (e.g., as a reaction to IsOverdueForSamplingAt()), the
  28. // bucket will underflow.
  29. if (!current_event_.is_null()) {
  30. if (current_event_ < event_time) {
  31. token_bucket_ += event_time - current_event_;
  32. if (token_bucket_ > token_bucket_capacity_)
  33. token_bucket_ = token_bucket_capacity_;
  34. }
  35. TRACE_COUNTER1("gpu.capture", "MirroringTokenBucketUsec",
  36. std::max<int64_t>(0, token_bucket_.InMicroseconds()));
  37. }
  38. current_event_ = event_time;
  39. }
  40. bool SmoothEventSampler::ShouldSample() const {
  41. return token_bucket_ >= min_capture_period_;
  42. }
  43. void SmoothEventSampler::RecordSample() {
  44. token_bucket_ -= min_capture_period_;
  45. if (token_bucket_.is_negative())
  46. token_bucket_ = base::TimeDelta();
  47. TRACE_COUNTER1("gpu.capture", "MirroringTokenBucketUsec",
  48. std::max<int64_t>(0, token_bucket_.InMicroseconds()));
  49. if (HasUnrecordedEvent())
  50. last_sample_ = current_event_;
  51. }
  52. bool SmoothEventSampler::HasUnrecordedEvent() const {
  53. return !current_event_.is_null() && current_event_ != last_sample_;
  54. }
  55. } // namespace media