File: overuse_detector.go

package info (click to toggle)
golang-github-pion-interceptor 0.1.12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, forky, sid, trixie
  • size: 764 kB
  • sloc: makefile: 8
file content (78 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package gcc

import (
	"time"
)

type threshold interface {
	compare(estimate time.Duration, delta time.Duration) (usage, time.Duration, time.Duration)
}

type overuseDetector struct {
	threshold   threshold
	overuseTime time.Duration

	dsWriter func(DelayStats)

	lastEstimate       time.Duration
	lastUpdate         time.Time
	increasingDuration time.Duration
	increasingCounter  int
}

func newOveruseDetector(thresh threshold, overuseTime time.Duration, dsw func(DelayStats)) *overuseDetector {
	return &overuseDetector{
		threshold:          thresh,
		overuseTime:        overuseTime,
		dsWriter:           dsw,
		lastEstimate:       0,
		lastUpdate:         time.Now(),
		increasingDuration: 0,
		increasingCounter:  0,
	}
}

func (d *overuseDetector) onDelayStats(ds DelayStats) {
	now := time.Now()
	delta := now.Sub(d.lastUpdate)
	d.lastUpdate = now

	thresholdUse, estimate, currentThreshold := d.threshold.compare(ds.Estimate, ds.LastReceiveDelta)

	use := usageNormal
	if thresholdUse == usageOver {
		if d.increasingDuration == 0 {
			d.increasingDuration = delta / 2
		} else {
			d.increasingDuration += delta
		}
		d.increasingCounter++
		if d.increasingDuration > d.overuseTime && d.increasingCounter > 1 {
			if estimate > d.lastEstimate {
				use = usageOver
			}
		}
	}
	if thresholdUse == usageUnder {
		d.increasingCounter = 0
		d.increasingDuration = 0
		use = usageUnder
	}

	if thresholdUse == usageNormal {
		d.increasingDuration = 0
		d.increasingCounter = 0
		use = usageNormal
	}
	d.lastEstimate = estimate

	d.dsWriter(DelayStats{
		Measurement:      ds.Measurement,
		Estimate:         estimate,
		Threshold:        currentThreshold,
		LastReceiveDelta: ds.LastReceiveDelta,
		Usage:            use,
		State:            0,
		TargetBitrate:    0,
	})
}