Home Reference Source

src/utils/ewma-bandwidth-estimator.ts

  1. /*
  2. * EWMA Bandwidth Estimator
  3. * - heavily inspired from shaka-player
  4. * Tracks bandwidth samples and estimates available bandwidth.
  5. * Based on the minimum of two exponentially-weighted moving averages with
  6. * different half-lives.
  7. */
  8.  
  9. import EWMA from '../utils/ewma';
  10.  
  11. class EwmaBandWidthEstimator {
  12. hls: any;
  13.  
  14. private defaultEstimate_: number;
  15. private minWeight_: number;
  16. private minDelayMs_: number;
  17. private slow_: EWMA;
  18. private fast_: EWMA;
  19.  
  20. // TODO(typescript-hls)
  21. constructor (hls: any, slow: number, fast: number, defaultEstimate: number) {
  22. this.hls = hls;
  23. this.defaultEstimate_ = defaultEstimate;
  24. this.minWeight_ = 0.001;
  25. this.minDelayMs_ = 50;
  26. this.slow_ = new EWMA(slow);
  27. this.fast_ = new EWMA(fast);
  28. }
  29.  
  30. sample (durationMs: number, numBytes: number) {
  31. durationMs = Math.max(durationMs, this.minDelayMs_);
  32. let numBits = 8 * numBytes,
  33. // weight is duration in seconds
  34. durationS = durationMs / 1000,
  35. // value is bandwidth in bits/s
  36. bandwidthInBps = numBits / durationS;
  37. this.fast_.sample(durationS, bandwidthInBps);
  38. this.slow_.sample(durationS, bandwidthInBps);
  39. }
  40.  
  41. canEstimate (): boolean {
  42. let fast = this.fast_;
  43. return (fast && fast.getTotalWeight() >= this.minWeight_);
  44. }
  45.  
  46. getEstimate (): number {
  47. if (this.canEstimate()) {
  48. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  49. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  50. // Take the minimum of these two estimates. This should have the effect of
  51. // adapting down quickly, but up more slowly.
  52. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  53. } else {
  54. return this.defaultEstimate_;
  55. }
  56. }
  57.  
  58. destroy () {
  59. }
  60. }
  61. export default EwmaBandWidthEstimator;