-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathbuffer.go
More file actions
481 lines (395 loc) · 9.61 KB
/
buffer.go
File metadata and controls
481 lines (395 loc) · 9.61 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jitter
import (
"math"
"sync"
"time"
"github.com/frostbyte73/core"
"github.com/go-logr/logr"
"github.com/pion/rtp"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/mono"
)
type ExtPacket struct {
ReceivedAt time.Time
*rtp.Packet
}
type Buffer struct {
depacketizer rtp.Depacketizer
latency time.Duration
logger logger.Logger
onPacket PacketFunc
onPacketLoss func()
mu sync.Mutex
closed core.Fuse
initialized bool
prevSN uint16
prevTS uint32
head *packet
tail *packet
stats *BufferStats
timer *time.Timer
pool *packet
size int
maxSequenceJump *uint16
maxTimestampJump *uint32
}
type Option func(*Buffer)
type BufferStats struct {
PacketsPushed uint64 // total packets pushed
PaddingPushed uint64 // padding packets pushed
PacketsLost uint64 // packets lost
PacketsDropped uint64 // packets dropped (incomplete)
PacketsPopped uint64 // packets sent to handler
SamplesPopped uint64 // samples sent to handler
}
type PacketFunc func(packets []ExtPacket)
func NewBuffer(
depacketizer rtp.Depacketizer,
latency time.Duration,
fnc PacketFunc,
opts ...Option,
) *Buffer {
b := &Buffer{
depacketizer: depacketizer,
latency: latency,
logger: logger.LogRLogger(logr.Discard()),
stats: &BufferStats{},
timer: time.NewTimer(latency),
onPacket: fnc,
}
for _, opt := range opts {
opt(b)
}
go func() {
for {
select {
case <-b.timer.C:
b.mu.Lock()
b.popReady()
b.mu.Unlock()
case <-b.closed.Watch():
return
}
}
}()
return b
}
func WithLogger(logger logger.Logger) Option {
return func(b *Buffer) {
b.logger = logger
}
}
func WithPacketLossHandler(handler func()) Option {
return func(b *Buffer) {
b.onPacketLoss = handler
}
}
func WithMaxSequenceJump(max uint16) Option {
return func(b *Buffer) {
b.maxSequenceJump = &max
}
}
func WithMaxTimestampJump(max uint32) Option {
return func(b *Buffer) {
b.maxTimestampJump = &max
}
}
func (b *Buffer) WithLogger(logger logger.Logger) *Buffer {
b.logger = logger
return b
}
func (b *Buffer) UpdateLatency(latency time.Duration) {
b.mu.Lock()
defer b.mu.Unlock()
b.latency = latency
if b.head != nil {
b.timer.Reset(time.Until(b.head.extPacket.ReceivedAt.Add(latency)))
}
}
func (b *Buffer) Push(pkt *rtp.Packet) {
b.PushAt(pkt, mono.Now())
}
func (b *Buffer) PushExtPacket(extPkt ExtPacket) {
b.PushAt(extPkt.Packet, extPkt.ReceivedAt)
}
func (b *Buffer) PushExtPacketBatch(extPktBatch []ExtPacket) {
for _, extPkt := range extPktBatch {
b.PushAt(extPkt.Packet, extPkt.ReceivedAt)
}
}
func (b *Buffer) PushAt(pkt *rtp.Packet, receivedAt time.Time) {
b.mu.Lock()
defer b.mu.Unlock()
b.push(pkt, receivedAt)
if b.head == nil {
return
}
b.popReady()
}
func (b *Buffer) Size() int {
b.mu.Lock()
defer b.mu.Unlock()
return b.size
}
func (b *Buffer) Stats() *BufferStats {
b.mu.Lock()
defer b.mu.Unlock()
return &BufferStats{
PacketsPushed: b.stats.PacketsPushed,
PaddingPushed: b.stats.PaddingPushed,
PacketsLost: b.stats.PacketsLost,
PacketsDropped: b.stats.PacketsDropped,
PacketsPopped: b.stats.PacketsPopped,
SamplesPopped: b.stats.SamplesPopped,
}
}
func (s *BufferStats) PacketLoss() float64 {
if s.PacketsPushed == 0 {
return 0
}
return float64(s.PacketsDropped) / float64(s.PacketsPushed)
}
func (b *Buffer) Close() {
b.timer.Stop()
b.closed.Break()
}
func (b *Buffer) isLargeTimestampJump(current, prev uint32) bool {
if b.maxTimestampJump == nil || !b.initialized {
return false
}
maxJump := uint32(*b.maxTimestampJump)
cur := int64(current)
prv := int64(prev)
forwardDiff := cur - prv
if forwardDiff < 0 {
forwardDiff += int64(math.MaxUint32) + 1
}
backwardDiff := prv - cur
if backwardDiff < 0 {
backwardDiff += int64(math.MaxUint32) + 1
}
return min(backwardDiff, forwardDiff) > int64(maxJump)
}
func (b *Buffer) isLargeSequenceJump(current, prev uint16) bool {
if b.maxSequenceJump == nil || !b.initialized {
return false
}
maxJump := int32(*b.maxSequenceJump)
cur := int32(current)
prv := int32(prev)
forwardDiff := cur - prv
if forwardDiff < 0 {
forwardDiff += int32(math.MaxUint16) + 1
}
backwardDiff := prv - cur
if backwardDiff < 0 {
backwardDiff += int32(math.MaxUint16) + 1
}
return min(backwardDiff, forwardDiff) > maxJump
}
func (b *Buffer) reset() {
b.logger.Infow("resetting jitter buffer due to RTP discontinuity")
dropped := 0
for b.head != nil {
next := b.head.next
if !b.head.extPacket.Padding {
dropped++
}
b.free(b.head)
b.head = next
}
b.tail = nil
if dropped > 0 {
b.stats.PacketsDropped += uint64(dropped)
if b.onPacketLoss != nil {
b.onPacketLoss()
}
}
b.initialized = false
b.prevSN = 0
b.prevTS = 0
if !b.timer.Stop() {
select {
case <-b.timer.C:
default:
}
}
b.timer.Reset(b.latency)
}
// push adds a packet to the buffer
func (b *Buffer) push(pkt *rtp.Packet, receivedAt time.Time) {
b.stats.PacketsPushed++
if pkt.Padding {
b.stats.PaddingPushed++
if !b.initialized {
return
}
}
if b.isLargeTimestampJump(pkt.Timestamp, b.prevTS) ||
b.isLargeSequenceJump(pkt.SequenceNumber, b.prevSN) {
b.logger.Infow("large RTP discontinuity detected",
"current_ts", pkt.Timestamp,
"prev_ts", b.prevTS,
"current_sn", pkt.SequenceNumber,
"prev_sn", b.prevSN,
)
b.reset()
}
if b.initialized && before(pkt.SequenceNumber, b.prevSN) {
// packet expired (not after discontinuity reset)
if !pkt.Padding {
b.stats.PacketsDropped++
if b.onPacketLoss != nil {
b.onPacketLoss()
}
}
return
}
p := b.newPacket(pkt, receivedAt)
discont := !b.initialized || !withinRange(pkt.SequenceNumber, b.prevSN)
if b.head == nil {
p.discont = discont && p.start
b.head = p
b.tail = p
return
}
beforeHead := before(pkt.SequenceNumber, b.head.extPacket.SequenceNumber)
afterTail := !before(pkt.SequenceNumber, b.tail.extPacket.SequenceNumber)
withinHeadRange := withinRange(pkt.SequenceNumber, b.head.extPacket.SequenceNumber)
withinTailRange := withinRange(pkt.SequenceNumber, b.tail.extPacket.SequenceNumber)
switch {
case beforeHead && withinHeadRange:
// prepend
p.discont = discont && p.start
b.head.prev = p
p.next = b.head
b.head = p
case afterTail && withinTailRange:
// append
p.prev = b.tail
b.tail.next = p
b.tail = p
case withinTailRange:
// insert, search from tail
for c := b.tail.prev; c != nil; c = c.prev {
discont = !withinRange(pkt.SequenceNumber, c.extPacket.SequenceNumber)
if !before(pkt.SequenceNumber, c.extPacket.SequenceNumber) || discont {
// insert after c
p.discont = discont && p.start
p.prev = c
p.next = c.next
c.next.prev = p
c.next = p
return
}
}
case withinHeadRange:
// insert, search from head
for c := b.head.next; c != nil; c = c.next {
discont = !withinRange(pkt.SequenceNumber, c.extPacket.SequenceNumber)
if before(pkt.SequenceNumber, c.extPacket.SequenceNumber) || discont {
// insert before c
p.prev = c.prev
p.next = c
c.prev.next = p
c.prev = p
return
}
}
default:
// append (discont)
p.discont = p.start
p.prev = b.tail
b.tail.next = p
b.tail = p
}
}
// popReady pushes all ready samples to the out channel
func (b *Buffer) popReady() {
expiry := time.Now().Add(-b.latency)
b.dropIncompleteExpired(expiry)
loss := false
for b.head != nil &&
b.head.isComplete() {
if b.head.extPacket.SequenceNumber == b.prevSN+1 || b.head.discont || !b.initialized {
// normal
} else if b.head.extPacket.ReceivedAt.Before(expiry) {
// max latency reached
loss = true
b.stats.PacketsLost += uint64(b.head.extPacket.SequenceNumber - b.prevSN - 1)
} else {
break
}
if sample := b.popSample(); len(sample) > 0 {
b.onPacket(sample)
}
}
if loss && b.onPacketLoss != nil {
b.onPacketLoss()
}
if b.head != nil {
b.timer.Reset(time.Until(b.head.extPacket.ReceivedAt.Add(b.latency)))
}
}
// dropIncompleteExpired drops incomplete expired packets
func (b *Buffer) dropIncompleteExpired(expiry time.Time) {
dropped := false
for b.head != nil && !b.head.isComplete() && b.head.extPacket.ReceivedAt.Before(expiry) {
if b.initialized && !b.head.discont {
b.stats.PacketsLost += uint64(b.head.extPacket.SequenceNumber - b.prevSN - 1)
}
b.free(b.popHead())
dropped = true
b.stats.PacketsDropped++
}
if dropped && b.onPacketLoss != nil {
b.onPacketLoss()
}
}
func (b *Buffer) popSample() []ExtPacket {
sample := make([]ExtPacket, 0, b.size)
end := false
for !end {
c := b.popHead()
end = c.end
if !c.extPacket.Padding {
sample = append(sample, c.extPacket)
}
b.stats.PacketsPopped++
b.free(c)
}
b.initialized = true
b.stats.SamplesPopped++
return sample
}
func (b *Buffer) popHead() *packet {
c := b.head
b.prevSN = c.extPacket.SequenceNumber
b.prevTS = c.extPacket.Timestamp
b.head = c.next
if b.head == nil {
b.tail = nil
} else {
b.head.prev = nil
}
return c
}
func before(a, b uint16) bool {
return (b-a)&0x8000 == 0
}
func withinRange(a, b uint16) bool {
return a-b < 3000 || b-a < 3000
}