/
throttling.go
72 lines (55 loc) · 1 KB
/
throttling.go
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
package socketfiles
import (
"time"
)
type throttler struct {
bitrate int
delay time.Duration
next *time.Timer
}
func (t *throttler) drain() {
if t.next == nil {
return
}
if !t.next.Stop() {
<-t.next.C
}
}
func (t *throttler) updateDelay(prescale int) {
if t.bitrate <= 0 {
t.delay = 0
t.drain()
t.next = nil
return
}
if t.next != nil {
t.drain()
t.next.Reset(0)
} else {
t.next = time.NewTimer(0)
}
// delay = nanoseconds per byte
t.delay = (8 * time.Second) / time.Duration(t.bitrate)
// recalculate to the actual expected maximum bitrate
t.bitrate = int(8 * time.Second / t.delay)
if prescale > 1 {
t.delay *= time.Duration(prescale)
}
}
func (t *throttler) throttle(scale int) {
if t.next == nil {
return
}
<-t.next.C
if scale > 1 {
t.next.Reset(time.Duration(scale) * t.delay)
return
}
t.next.Reset(t.delay)
}
func (t *throttler) setBitrate(bitrate, prescale int) int {
prev := t.bitrate
t.bitrate = bitrate
t.updateDelay(prescale)
return prev
}