-
Notifications
You must be signed in to change notification settings - Fork 51
/
leaky_bucket_pacer.go
166 lines (139 loc) · 3.98 KB
/
leaky_bucket_pacer.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package gcc
import (
"container/list"
"errors"
"sync"
"time"
"github.com/pion/interceptor"
"github.com/pion/logging"
"github.com/pion/rtp"
)
var errLeakyBucketPacerPoolCastFailed = errors.New("failed to access leaky bucket pacer pool, cast failed")
type item struct {
header *rtp.Header
payload *[]byte
size int
attributes interceptor.Attributes
}
// LeakyBucketPacer implements a leaky bucket pacing algorithm
type LeakyBucketPacer struct {
log logging.LeveledLogger
f float64
targetBitrate int
targetBitrateLock sync.Mutex
pacingInterval time.Duration
qLock sync.RWMutex
queue *list.List
done chan struct{}
ssrcToWriter map[uint32]interceptor.RTPWriter
writerLock sync.RWMutex
pool *sync.Pool
}
// NewLeakyBucketPacer initializes a new LeakyBucketPacer
func NewLeakyBucketPacer(initialBitrate int) *LeakyBucketPacer {
p := &LeakyBucketPacer{
log: logging.NewDefaultLoggerFactory().NewLogger("pacer"),
f: 1.5,
targetBitrate: initialBitrate,
pacingInterval: 5 * time.Millisecond,
qLock: sync.RWMutex{},
queue: list.New(),
done: make(chan struct{}),
ssrcToWriter: map[uint32]interceptor.RTPWriter{},
pool: &sync.Pool{},
}
p.pool = &sync.Pool{
New: func() interface{} {
b := make([]byte, 1460)
return &b
},
}
go p.Run()
return p
}
// AddStream adds a new stream and its corresponding writer to the pacer
func (p *LeakyBucketPacer) AddStream(ssrc uint32, writer interceptor.RTPWriter) {
p.writerLock.Lock()
defer p.writerLock.Unlock()
p.ssrcToWriter[ssrc] = writer
}
// SetTargetBitrate updates the target bitrate at which the pacer is allowed to
// send packets. The pacer may exceed this limit by p.f
func (p *LeakyBucketPacer) SetTargetBitrate(rate int) {
p.targetBitrateLock.Lock()
defer p.targetBitrateLock.Unlock()
p.targetBitrate = int(p.f * float64(rate))
}
func (p *LeakyBucketPacer) getTargetBitrate() int {
p.targetBitrateLock.Lock()
defer p.targetBitrateLock.Unlock()
return p.targetBitrate
}
// Write sends a packet with header and payload the a previously registered
// stream.
func (p *LeakyBucketPacer) Write(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) {
buf, ok := p.pool.Get().(*[]byte)
if !ok {
return 0, errLeakyBucketPacerPoolCastFailed
}
copy(*buf, payload)
hdr := header.Clone()
p.qLock.Lock()
p.queue.PushBack(&item{
header: &hdr,
payload: buf,
size: len(payload),
attributes: attributes,
})
p.qLock.Unlock()
return header.MarshalSize() + len(payload), nil
}
// Run starts the LeakyBucketPacer
func (p *LeakyBucketPacer) Run() {
ticker := time.NewTicker(p.pacingInterval)
defer ticker.Stop()
lastSent := time.Now()
for {
select {
case <-p.done:
return
case now := <-ticker.C:
budget := int(float64(now.Sub(lastSent).Milliseconds()) * float64(p.getTargetBitrate()) / 8000.0)
p.qLock.Lock()
for p.queue.Len() != 0 && budget > 0 {
p.log.Infof("budget=%v, len(queue)=%v, targetBitrate=%v", budget, p.queue.Len(), p.getTargetBitrate())
next, ok := p.queue.Remove(p.queue.Front()).(*item)
p.qLock.Unlock()
if !ok {
p.log.Warnf("failed to access leaky bucket pacer queue, cast failed")
continue
}
p.writerLock.RLock()
writer, ok := p.ssrcToWriter[next.header.SSRC]
p.writerLock.RUnlock()
if !ok {
p.log.Warnf("no writer found for ssrc: %v", next.header.SSRC)
p.pool.Put(next.payload)
p.qLock.Lock()
continue
}
n, err := writer.Write(next.header, (*next.payload)[:next.size], next.attributes)
if err != nil {
p.log.Errorf("failed to write packet: %v", err)
}
lastSent = now
budget -= n
p.pool.Put(next.payload)
p.qLock.Lock()
}
p.qLock.Unlock()
}
}
}
// Close closes the LeakyBucketPacer
func (p *LeakyBucketPacer) Close() error {
close(p.done)
return nil
}